[英]Access UNIX server and run a shell script from java application
我有一個要求,我必須訪問一個 unix 服務器,並且在該服務器上我必須運行一個帶有來自我的 java 應用程序的一些參數的 shell 腳本。 請舉例提出一些解決方案。
我試過一些東西,但它不起作用。
SshWrapper ssh = new SshWrapper();
try {
ssh.connect("10.206.19.80", 22);
ssh.login("*****","*****");
ssh.setPrompt("c898vqz:~");
ssh.waitfor("#");
System.out.println("PWD**********"+ssh.send("pwd"));
ssh.disconnect();
System.out.println(ssh.getClass());
} catch (java.io.IOException e) {
e.printStackTrace();
}
從ssh.send("pwd")
獲取null
您可以使用SSH
組件JCraft
進行遠程連接和 shell 命令調用:
import com.jcraft.jsch.*
Exerp 來自我的舊代碼:
JSch jsch = new JSch();
String command = "/tmp/myscript.sh";
Session session = jsch.getSession(user, host, 22);
session.connect();
Channel channel = session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) {
break;
}
System.out.print(new String(tmp, 0, i));
}
if (channel.isClosed()) {
if (channel.getExitStatus() == 0) {
System.out.println("Command executed successully.");
}
break;
}
}
channel.disconnect();
session.disconnect();
您還可以通過session.openChannel("sftp")
輕松傳輸文件。
哎呀..在java
它太羅嗦了,而不是在ruby
或python
:)
JSch js = new JSch();
Session s = js.getSession("username", "ip", port);
s.setPassword("password");
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
s.setConfig(config);
s.connect();
System.out.println("connection ");
Channel c = s.openChannel("sftp");
ChannelSftp ce = (ChannelSftp) c;
ce.connect();
System.out.println("connection ");
ce.disconnect();
s.disconnect();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.