java远程调用ssh
业务系统部署在docker容器中,需要调用fastfdfs服务器命令上传到服务器中,并在系统中记录路径
本文引用jsch
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch --> <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency>
/** * 连接到指定的IP * * @throws JSchException */ public void connect() throws JSchException { jsch = new JSch(); jsch.addIdentity(keyFile); session = jsch.getSession(user, host, 22); //session.setPassword(passwd);如果用密码模式 java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); }
public String execCmd(String cmd) { String command = cmd; BufferedReader reader = null; Channel channel = null; try { channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); channel.connect(); InputStream in = channel.getInputStream(); reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset))); String buf = ""; String cmdResult = ""; while ((buf = reader.readLine()) != null) { String temp = buf; cmdResult = cmdResult + temp; } return cmdResult; } catch (IOException e) { LOGGER.info(e.getMessage()); return ""; } catch (JSchException e) { LOGGER.info(e.getMessage()); return ""; } finally { try { reader.close(); } catch (IOException e) { LOGGER.info(e.getMessage()); } channel.disconnect(); //session.disconnect(); }
//上传命令 //将文件保存到fastfdfs文件服务器中 返回 group1/M01/1D/E3/rBADlVcHC1OAdGkQAABDEJGMKGI112.png String upCmd = "fdfs_upload_file " + fdfsConfig + " \"" + ftpDir + fileName + "\""; String fileId = sshUtils.execCmd(upCmd); if (fileId.contains("<config_file>")) { return; } logger.info("upload ftp File result={}", fileId); //删除文件 String delCmd = "rm -f \"" + ftpDir + fileName + "\""; sshUtils.execCmd(delCmd);
证书生成
[root@172-16-3-82 ~]# cd .ssh/ [root@172-16-3-82 .ssh]# [root@172-16-3-82 .ssh]# [root@172-16-3-82 .ssh]# ls authorized_keys authorized_keys.bak id_rsa_1024.pub [root@172-16-3-82 .ssh]# [root@172-16-3-82 .ssh]# [root@172-16-3-82 .ssh]# [root@172-16-3-82 .ssh]# rz -y . waiting to receive.**B0100000023be50 [root@172-16-3-82 .ssh]# ls authorized_keys authorized_keys.bak id_rsa_1024.pub id_rsa_test.pub [root@172-16-3-82 .ssh]# [root@172-16-3-82 .ssh]# cat id_rsa_test.pub >>authorized_keys