//调用远程服务器的shell脚本
//ip:远程服务器的ip地址
//username:远程服务器的登录用户名
//port:远程服务器的登录端口号
//cmd:登录之后的命令
public Response<Boolean> runRemoteShell(String ip,String username,Integer port,String cmd) throws JSchException, IOException {
try {
JSch jsch = new JSch();
// Endpoint以杭州为例,其它Region请按实际情况填写。
String endpoint = "http://oss-cn-shanghai.aliyuncs.com";
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
String accessKeyId = "********";
String accessKeySecret = "********";
String bucketName = "********";
String objectName = "********";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
// 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File("data.pem"));
// 关闭OSSClient。
ossClient.shutdown();
//从阿里云Oss上面下载密钥文件
jsch.addIdentity("data.pem");
Session session=jsch.getSession(username, ip, port);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(); //建立会话
ChannelShell channelShell= (ChannelShell) session.openChannel("shell");
channelShell.connect();
InputStream inputStream=channelShell.getInputStream();
OutputStream outputStream = channelShell.getOutputStream();
PrintWriter printWriter = new PrintWriter(outputStream); //建立通道
printWriter.println(cmd); //输入命令
printWriter.println("exit"); //输入结束操作命令
printWriter.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String msg; //在控制台上打印远程服务器的显示结果
while((msg = in.readLine())!=null){
System.out.println(msg);
}
in.close();
return new Response<>("脚本执行成功",Response.SUCCESS_CODE,Boolean.TRUE);
}catch (JSchException e) {
e.printStackTrace();
return new Response<>("登入远程服务器失败");
}
}