java操作Linux服务器可以使用专用的jar包,这里介绍使用jsch操作Linux服务器
maven 依赖
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
引入包以后 获取ssh连接
public static ChannelShell connectShell(Session session) {
ChannelShell shell = null;
try {
shell = (ChannelShell) session.openChannel(type_ssh);
shell.connect();
System.out.println();
System.out.println("shell resource:" + session.equals(shell.getSession()));
System.out.println("shell login ok:" + shell.getId());
System.out.println();
return shell;
} catch (Exception e) {
e.printStackTrace();
}
return shell;
}
以上获取到连接对象可以进行交互操作,在调用方法中定义接收流对象后可以交互执行命令
一下监听和发送都在一个线程中,所以开启定时任务发送命令,主进程监听消息获取
getMsg为接收消息方法
private static PrintStream commander;//定义常量 发送消息使用
BufferedReader br;
try {
OutputStream outputStream = myShellSession_.getChannelShell().getOutputStream();
InputStream inputStream = myShellSession_.getChannelShell().getInputStream();
commander = new PrintStream(outputStream, false, MyShellAndSftpUtils.ENCODING);
br = new BufferedReader(new InputStreamReader(inputStream, MyShellAndSftpUtils.ENCODING));
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
sendMsg("pwd");//定时发送消息
System.out.println("shell run , time is "+DataTimeUtils.getDataStrOut());
}
},0,DataTimeUtils.getaLong(myShellSession_.getConfigParams().getShellTime()));//立即执行 过15分执行 15分 * 60 秒 * 1000毫秒
try {
getMsg();
} catch (Exception e) {
e.printStackTrace();
}
//接收消息调用
public static void getMsg() throws Exception {
StringBuffer buffer = new StringBuffer();
String line;
boolean flag = false;
while ((line = br.readLine()) != null) {
System.out.println("line " + line);
if (line.startsWith("Starting Nmap")) {
flag = true;
}
if (flag) {
buffer.append(line);
buffer.append(MyShellAndSftpUtils.lineSeparator);
}
if (line.startsWith("****:")) {//检测返回信息的开始
flag = false;
saveDb(buffer.toString());//执行存储等逻辑
buffer.setLength(0);
}
}
}
public static void sendMsg(String msg) {标签:shell,java,System,SSH,new,println,服务器,line,out From: https://www.cnblogs.com/CaiNiao-TuFei/p/16592363.html
commander.println(msg);
commander.flush();
}
以上方案可以连续执行命令,但是返回的结果需要进行判断后才能进入自己的操作