我们的内网服务器每次更新前后端包时,都要先登陆一个普通xunjian帐号,再切换成root输入密码,上传包后再用命令更新,操作有点麻烦,所以用JSch写了一个工具类来实现密码输入和用户的切换以及项目包的上传和更新,下面是代码
java
import com.jcraft.jsch.*;
import java.io.*;
import java.util.concurrent.TimeUnit;
public class Update {
public static String user="xunjian";
public static String host="10.10.10.124";
public static int port=10022;
public static String password="123456";
public static String rootpassword="abcdef";
public static void main(String[] args) {
try {
JSch jsch = new JSch();
Session session = jsch.getSession(user,host,port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
ChannelShell channel = (ChannelShell)session.openChannel("shell");
ChannelSftp sftp =(ChannelSftp) session.openChannel("sftp");
//执行命令的通道
channel.connect();
//上传包的sftp通道
sftp.connect();
final BufferedReader i = new BufferedReader(new InputStreamReader(channel.getInputStream()));
//另起一线程去处理服务器输出
new Thread(new Runnable(){
@Override
public void run() {
try {
String line;
while ((line=i.readLine())!=null){
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
},"read").start();
//写入流,用于命令的写入
OutputStream o = channel.getOutputStream();
//切换用户
commond("su - root",o);
//我在外网测试时,这里不等待无法正常切换root,不知道啥原因
TimeUnit.SECONDS.sleep(1);
commond(rootpassword,o);
//删除之前包
rm("/home/xm.jar",sftp);
//把正在运行包改名
rename("/home/xm.jar",sftp);
//上传新jar包
sftp.put(new FileInputStream("C:\\Users\\Administrator\\Desktop\\a\\xm.jar"),"/home/xm.jar",ChannelSftp.OVERWRITE);
System.out.println("包上传完成,正在更新...");
//更新命令也可以分开输入
commond("/home/stop.sh && /home/start.sh",o);
session.disconnect();
System.out.println("更新完成");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void commond(String c,OutputStream o){
try {
o.write(c.getBytes());
o.write("\n\r".getBytes());
o.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void rm(String path,ChannelSftp sftp){
try {
sftp.rm(path+".bak");
} catch (SftpException e) {
}
}
public static void rename(String path,ChannelSftp sftp){
try {
sftp.rename(path,path+".bak");
} catch (SftpException e) {
}
}
}