一 需求描述:
通常我们操作linux服务器都是通过远程连接工具,比如:SecureCRT,Xmanager等工具,在其上输入命令来完成一些工作,但是在实际工作中,有些时候需要我们通过java代码远程连接到linux服务器执行一些shell命令,包括集群的状态管理,执行任务,以及集群的可视化界面操作等等。为了解决上述的问题,google公司开源了一个项目叫做sshxcute,通过这个jar包可以操作linucx服务器。
sshxcute项目的地址:
https://code.google.com/archive/p/sshxcute/
sshxcute的使用说明:
https://www.ibm.com/developerworks/cn/opensource/os-sshxcute/
二 入门案列
1 在idea或者eclipse开发工具中创建maven的java工程,并导入jar包,由于sshxcute.jar这个jar包没有maven的坐标,需要手动导入到工程的build path当中去
2 开发代码
public static void main(String[] args) throws TaskExecFailException {
//连接到linux服务器
//第一个参数是我们要连接的linux的服务器的ip地址
//第二个参数是 linux服务器的用户
//第三个参数是 linux服务器的用户对应的密码
ConnBean connBean = new ConnBean("192.168.52.100", "root", "123456");
SSHExec instance = SSHExec.getInstance(connBean);
instance.connect();
//执行shell命令
//echo 'hello world' > /export/servers/demo.txt 这个shell命令是把hello world 写入demo.txt文件中,并覆盖文件的原来内容
ExecCommand execCommand = new ExecCommand("echo 'hello world' > /export/servers/demo.txt");
instance.exec(execCommand);
instance.disconnect();
}
3 进入linux服务器,查看demo.txt的内容是否为hello world,如果是代表你已经操作成功了!
thank you!