java 调用Linux shell

java通过ssh操作linux服务器
http://blog.csdn.net/u012621115/article/details/53434548

调用命令

final Process process = Runtime.getRuntime().exec(command);
BufferedReader bufReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

http://www.cnblogs.com/langtianya/p/6815976.html

特别需要注意的是,当需要执行的linux命令带有管道符时(例如:ps -ef|grep java),用上面的方法是不行的,解决方式是将需要执行的命令作为参数传给shell

final String[] command={"/bin/sh","-c","/usr/bin/cat /proc/cpuinfo | grep 'cpu cores' | uniq"};

http://blog.csdn.net/a19881029/article/details/8063758

command 命令可以是缩写,也可以加该命令的路径

/usr/bin/cat 是可以的
cat 也是可以的

同时,| 无需转义

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Java调用远程主机上的shell,你可以使用JSch库。JSch是一个Java实现的SSH2协议客户端,它可以让你在Java程序中连接到远程服务器,并执行shell命令。 以下是一个简单的示例代码,可以连接到远程Linux主机并执行一个shell命令: ```java import com.jcraft.jsch.*; public class SSHCommandExecutor { public static void main(String[] args) { String host = "your_remote_host"; String user = "your_username"; String password = "your_password"; String command = "ls -l"; try { JSch jsch = new JSch(); Session session = jsch.getSession(user, host, 22); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); byte[] tmp = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); if (i < 0) break; System.out.print(new String(tmp, 0, i)); } if (channel.isClosed()) { if (in.available() > 0) continue; System.out.println("exit-status: " + channel.getExitStatus()); break; } try { Thread.sleep(1000); } catch (Exception ee) { } } channel.disconnect(); session.disconnect(); } catch (JSchException | IOException e) { e.printStackTrace(); } } } ``` 在这个示例中,我们使用JSch连接到远程主机,并执行一个简单的shell命令“ls -l”。你可以将这个命令替换成任何你想要在远程主机上执行的命令。注意,你需要将“your_remote_host”,“your_username”和“your_password”替换为你自己的主机名,用户名和密码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值