我正在嘗試將我的更改推送到 GitLab,它允許我在機器上啟動本地服務器并使用密鑰身份驗證通過 SFTP 連接到它。在我的本地運行時,所有測驗都按預期通過,我可以連接到 Apache Mina 服務器。然而,當測驗在 GitLab 管道上運行時,我得到一個權限被拒絕錯誤,幾乎沒有解釋。對此的任何見解都會非常有幫助。一旦到達sshd.start()就是拋出例外的時候
提前致謝。
java.net.SocketException: Permission denied
at sun.nio.ch.Net.bind0(Native Method)
at sun.nio.ch.Net.bind(Net.java:433)
at sun.nio.ch.Net.bind(Net.java:425)
at sun.nio.ch.AsynchronousServerSocketChannelImpl.bind(AsynchronousServerSocketChannelImpl.java:162)
at org.apache.sshd.common.io.nio2.Nio2Acceptor.bind(Nio2Acceptor.java:83)
at org.apache.sshd.common.io.nio2.Nio2Acceptor.bind(Nio2Acceptor.java:173)
at org.apache.sshd.server.SshServer.start(SshServer.java:340)
at com.broadridge.gto.gptm.recon.controller.BPSDataLoadControllerTest.startSftpServer(BPSDataLoadControllerTest.java:162)
at com.broadridge.gto.gptm.recon.controller.BPSDataLoadControllerTest.bpsSftpDataLoad(BPSDataLoadControllerTest.java:120)
控制器:
try {
sftp.execute(
downloadFileInto(
"/path/to/file/test",
positionService::saveAllBpsPositionData));
測驗:
@Test
void bpsSftpDataLoad() throws Throwable {
ReflectionTestUtils.setField(dataLoadController, "wildcard", "test");
startSftpServer();
InputStream is =
new ClassPathResource("/testdata/PositionRecon/position.txt").getInputStream();
Path virtualFile =
fileSystem.getPath("/path/to/file/test");
java.nio.file.Files.createDirectories(virtualFile.getParent());
java.nio.file.Files.createFile(virtualFile);
java.nio.file.Files.copy(is, virtualFile, StandardCopyOption.REPLACE_EXISTING);
mockMvc.perform(
MockMvcRequestBuilders.request(
HttpMethod.POST, "/perform-bps-load-sftp/{businessDate}", "06072022"));
assertEquals(8, bpsPositionsRepo.countByBusinessDate(LocalDate.parse("2022-06-07")));
assertEquals(3, bpsPriceRepo.countByBusinessDate(LocalDate.parse("2022-06-07")));
assertEquals(2, bpsMemoRepo.countByBusinessDate(LocalDate.parse("2022-06-07")));
teardown();
}
private void startSftpServer()
throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
sshd = SshServer.setUpDefaultServer();
sshd.setPort(port);
sshd.setSubsystemFactories(
Collections.singletonList(new SftpSubsystemFactory.Builder().build()));
sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
sshd.setUserAuthFactories(
BuiltinUserAuthFactories.parseFactoriesList("publickey").getParsedFactories());
sshd.setPublickeyAuthenticator(
new KeySetPublickeyAuthenticator(
"keySetPKAuth",
SftpTestConfigUtils.loadPemPublicKeys(
new ClassPathResource("/keystore/public_test.pem"))));
fileSystem =
Jimfs.newFileSystem(Configuration.unix().toBuilder().setAttributeViews("posix").build());
sshd.setFileSystemFactory(new VirtualFileSystemFactory(fileSystem.getPath("/")));
sshd.start();
}
配置:
public class SftpTestConfigUtils {
public static Set<PublicKey> loadPemPublicKeys(Resource... resources)
throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
Set<PublicKey> publicKeySet = new HashSet<>();
for (Resource resource : resources) {
try (InputStream inputStream = resource.getInputStream();
Reader reader = new InputStreamReader(inputStream);
PemReader pemReader = new PemReader(reader)) {
PemObject pemObject =
Objects.requireNonNull(pemReader.readPemObject(), "No public key found in " resource);
publicKeySet.add(keyFactory.generatePublic(new X509EncodedKeySpec(pemObject.getContent())));
}
}
return publicKeySet;
}
public static FailableSupplier<Session, JSchException> getConfig(int port) {
SftpConfiguration config = new SftpConfiguration();
config.setPort(port);
config.setServer("127.0.0.1");
config.setUsername("sshd");
config.setPrivateKey(new ClassPathResource("/keystore/test_pk_rsa_mina.pem"));
return config::createSession;
}
}
@Configuration
public class SftpSpringConfiguration {
@Bean
@ConfigurationProperties(prefix = "recon.data.load.sftp.*")
public SftpConfiguration sftpFileRetrievalConfiguration() {
return new SftpConfiguration();
}
@Bean
public SftpFileRetrieval fileRetrieval() {
return new SftpFileRetrieval(sftpFileRetrievalConfiguration()::createSession);
}
}
@NoArgsConstructor
@Getter
@Setter
public class SftpConfiguration {
private String server;
private String username;
private Resource privateKey;
private int port;
public Session createSession() throws JSchException {
validate();
JSch jsch = new JSch();
try {
byte[] privateKeyBytes = IOUtils.toByteArray(this.getPrivateKey().getInputStream());
jsch.addIdentity("user", privateKeyBytes, null, null);
Arrays.fill(privateKeyBytes, (byte) 0); // Go away Checkmarx!
} catch (IOException e) {
throw new RuntimeException("Failed to read private key", e);
}
Session session = jsch.getSession(this.getUsername(), this.getServer(), this.getPort());
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
return session;
}
SFTP 客戶端:
public SftpFileRetrieval(@NonNull FailableSupplier<Session, JSchException> sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public void execute(FailableConsumer<ChannelSftp, Exception> consumer) throws Exception {
Session session =
Objects.requireNonNull(sessionFactory.get(), "Null session returned from session factory.");
ChannelSftp channelSftp = null;
try {
session.connect();
channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
log.info("SFTP channel connected");
consumer.accept(channelSftp);
} catch (Exception e) {
log.warn("Sftp File Retrieval Failed: {}", e.getMessage());
throw e;
} finally {
if (channelSftp != null) {
closeQuietly(channelSftp::disconnect);
closeQuietly(channelSftp::exit);
}
closeQuietly(session::disconnect);
}
}
注意:我的 SftpConfiguration 類的所有值都由 SpringConfig 類自動裝配,這些值位于我的 application.yml
讓我認為這是一個 GitLab 問題的原因是,再次在我的本地系統上運行它時,所有測驗都按預期通過,并且我在連接、寫入、從服務器下載時沒有問題。
如果您需要查看更多代碼,請告訴我。
uj5u.com熱心網友回復:
該錯誤表明 SFTP 服務器邏輯在系結到 TCP 埠以接收連接時出錯。您表示它正在嘗試系結到埠 22。
在 unix 系統上,不以 root 身份運行的行程通常無法系結到低于 1024 的埠。這是為了防止不受信任的行程接管基本服務使用的埠。
也有可能其他行程已經系結到埠 22。埠 22 是標準的 SSH 服務埠,大多數 unix 系統運行 SSH 服務器來提供遠程訪問。如果您的測驗服務器可以系結到埠 22,它可能會發現自己正在接收來自未參與測驗的真正 SSH 客戶端的連接。
除非您想以 root 身份運行測驗并且確定埠 22 未被使用,否則您應該安排測驗使用 1024 到 65535 范圍內的埠號。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/521733.html
