java ssh shell命令_java 通过ssh 执行命令
java 里面的開源 ssh lib
jsch 例子
JSch jSch = new JSch();
//設置JSch 的日志,可以看到具體日志信息
JSch.setLogger(new Logger() {
@Override
public boolean isEnabled(int level) {
return true;
}
@Override
public void log(int level, String message) {
System.out.println("logger:" + message);
}
});
com.jcraft.jsch.Session session = jSch.getSession("king", "127.0.0.1");
session.setPassword("123456");
//忽略hostkey 檢查
session.setConfig("StrictHostKeyChecking", "no");
//設置需要kerbores 驗證 鍵盤交互 忽略
session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
session.connect(60000);
//開啟shell,shell 具有上下文交互,執行命令不會馬上退出
ChannelShell shell = (ChannelShell) session.openChannel("shell");
//開始 exec 類似linux bash -c exec 執行完命令馬上退出
//ChannelExec exec = (ChannelExec)session.openChannel("exec");
//exec.setCommand("");
shell.setPtyType("dumb");
shell.setPty(true);
shell.connect(60000);
boolean connected = shell.isConnected();
OutputStream outputStream = shell.getOutputStream();
InputStream inputStream = shell.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
//通過流寫入命令
outputStream.write("pwd\n cd /home\nls\npwd\n".getBytes());
outputStream.flush();
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
sshj 例子
DefaultConfig defaultConfig = new DefaultConfig();
final SSHClient client = new SSHClient(defaultConfig);
String host = "127.0.0.1";
String user = "king";
String password = "123456";
client.setTimeout(60000);
client.loadKnownHosts();
client.addHostKeyVerifier(new PromiscuousVerifier());
client.connect(host);
try {
client.authPassword(user, password);
final SessionChannel session = (SessionChannel) client.startSession();
session.allocateDefaultPTY();
//這里的session 類似 jsch 里面的exec ,可以直接執行命令。
//session.exec("pwd");
SessionChannel shell = (SessionChannel) session.startShell();
try {
OutputStream outputStream = shell.getOutputStream();
outputStream.write("pwd\n".getBytes());
outputStream.flush();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(shell.getInputStream(), "utf-8"));
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} finally {
client.disconnect();
}
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的java ssh shell命令_java 通过ssh 执行命令的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 华为手机怎么投屏?
- 下一篇: “形音谁赏录”上一句是什么
