java使用ssh连接linux并执行命令
时间: 2023-07-25 07:04:20 浏览: 57
可以使用JSch库来在Java中使用SSH连接Linux并执行命令。以下是一个示例代码:
```java
import com.jcraft.jsch.*;
public class SSHCommandExecutor {
public static void main(String[] args) {
String host = "your_host";
String user = "your_username";
String password = "your_password";
String command = "your_command";
try {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
Channel channel = session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
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(in.available()>0) continue;
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception e){}
}
channel.disconnect();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
你需要将 `your_host`,`your_username`,`your_password` 和 `your_command` 替换为你的实际值。这个示例代码使用了 `System.out` 来输出命令执行的结果,你可以根据需要进行修改。