Java uses JSch to connect to the server to realize command interaction
1. Import jsch through maven
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
2. Code writing
Here, the Linux server is connected remotely through jsch, and the command interaction is realized on the console.
(1) Create MyUserInfo
Create a UserInfo class and implement the UserInfo interface (required) and the UIKeyboardInteractive interface (optional). Change the return value of the public boolean promptYesNo(String s) method to true.
public class MyUserInfo implements UserInfo, UIKeyboardInteractive {
@Override
public String getPassphrase() {
return null;
}
@Override
public String getPassword() {
return null;
}
@Override
public boolean promptPassword(String s) {
return false;
}
@Override
public boolean promptPassphrase(String s) {
return false;
}
/*====这里====*/
@Override
public boolean promptYesNo(String s) {
//return false;
return true;
}
@Override
public void showMessage(String s) {
}
@Override
public String[] promptKeyboardInteractive(String s, String s1, String s2, String[] strings, boolean[] booleans) {
return null;
}
}
(2) Create a Shell class to connect to the server
public class Shell {
/**
*
* @param host 服务器ip地址
* @param username 用户名
* @param password 密码
* @param port 端口
*/
public void show(String host,String username,String password,int port){
try {
//1、创建JSch对象
JSch jSch = new JSch();
//2、设置连接服务器参数
//用户名、主机ip、端口 获取session
Session session = jSch.getSession(username, host, port);
//设置密码
session.setPassword(password);
//设置用户信息(必须)
session.setUserInfo(new MyUserInfo());
//设置session连接超时时间
session.connect(30000);
//3、设置操作服务器的方式
//采用shell方式(即命令交互)
Channel channel = session.openChannel("shell");
//命令从控制台输入
channel.setInputStream(System.in);
//显示信息从控制台输出
channel.setOutputStream(System.out);
//设置命令执行超时时间
channel.connect(3*1000);
} catch (JSchException e) {
e.printStackTrace();
}
}
}
(3) start
Make sure that port 22 of the linux server is open before starting.
public class AppMain {
public static void main(String[] args) throws InterruptedException {
String username="root";//用户名
String host="100.100.100.100";//ip地址
int port=22;//端口 22端口,即为ssh应用端口,远程连接端口
String password="123456789";//密码
Shell shell = new Shell();
shell.show(host,username,password,port);
}
}
3. Test results
When the main function is started, the console can be used as a shell to interact with linux commands.