当前位置: 移动技术网 > IT编程>开发语言>Java > Java中通过jsch来连接远程服务器执行linux命令

Java中通过jsch来连接远程服务器执行linux命令

2019年07月22日  | 移动技术网IT编程  | 我要评论

有时候你可能需要通过代码来控制执行linux命令实现某些功能。

针对这类问题可以使用jsch来实现,具体代码如下:

public class cogradientimgfilemanager{
private static final logger log = loggerfactory.getlogger(cogradientimgfilemanager.class);
private static channelexec channelexec;
private static session session = null;
private static int timeout = 60000; 
// 测试代码
public static void main(string[] args){
try{
versousshutil("10.8.12.189","jmuser","root1234",22);
runcmd("java -version","utf-8");
}catch (exception e){
// todo auto-generated catch block
e.printstacktrace();
}
}
/**
* 连接远程服务器
* @param host ip地址
* @param username 登录名
* @param password 密码
* @param port 端口
* @throws exception
*/
public static void versousshutil(string host,string username,string password,int port) throws exception{
log.info("尝试连接到....host:" + host + ",username:" + username + ",password:" + password + ",port:"
+ port);
jsch jsch = new jsch(); // 创建jsch对象
session = jsch.getsession(username, host, port); // 根据用户名,主机ip,端口获取一个session对象
session.setpassword(password); // 设置密码
properties config = new properties();
config.put("stricthostkeychecking", "no");
session.setconfig(config); // 为session对象设置properties
session.settimeout(timeout); // 设置timeout时间
session.connect(); // 通过session建立链接
}
/**
* 在远程服务器上执行命令
* @param cmd 要执行的命令字符串
* @param charset 编码
* @throws exception
*/
public static void runcmd(string cmd,string charset) throws exception{
channelexec = (channelexec) session.openchannel("exec");
channelexec.setcommand(cmd);
channelexec.setinputstream(null);
channelexec.seterrstream(system.err);
channelexec.connect();
inputstream in = channelexec.getinputstream();
bufferedreader reader = new bufferedreader(new inputstreamreader(in, charset.forname(charset)));
string buf = null;
while ((buf = reader.readline()) != null){
system.out.println(buf);
}
reader.close();
channelexec.disconnect();
}
}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网