java ssh shell命令_java连接ssh执行shell脚本

在liunx上写了一个shell脚本,想通过java去调用这个shell脚本,不知道怎么去调用,在网上说使用process这个进程方式,但是我执行机和我shell脚本都不在同一台电脑,老大说java中可以连接ssh,执行shell脚本,以下代码来自他们以前的项目

public class SSH {

static Connection conn = null;

static String hostname = "XXXiP地址2";

static String username = "root";

static String password = "zhou123";

static int port = 36000;

public static void connect()

throws IOException {

try {

conn = new Connection(hostname,port);

conn.connect();

conn.authenticateWithPassword(username, password);

} catch (Exception e) {

System.out.println("ִ���쳣");

System.out.println("" + e);

}

}

@SuppressWarnings("resource")

public static String execCommand(String command) throws IOException {

connect();

Session session = conn.openSession();

session.execCommand(command);

StreamGobbler stdout = new StreamGobbler(session.getStdout());

BufferedReader br = new BufferedReader(new InputStreamReader((stdout),

"UTF-8"));

String line = "";

while ((line = br.readLine()) != null) {

System.out.println(line);

}

session.close();

return line;

}

@SuppressWarnings("resource")

public static ArrayList execCommandd(String command)

throws IOException {

connect();

Session session = conn.openSession();

session.execCommand(command);

ArrayList array_result = new ArrayList();

StreamGobbler stdout = new StreamGobbler(session.getStdout());

BufferedReader br = new BufferedReader(new InputStreamReader((stdout),

"UTF-8"));

String line;

while ((line = br.readLine()) != null) {

array_result.add(line);

}

session.close();

return array_result;

}

public static void main(String[] args) {

try {

// System.out.println( execCommandd("uname -s -r -v"));

System.out.println( execCommandd("pwd"));//使用的sh方式执行

System.out.println( execCommandd("sh /script/test3.sh"));//使用的sh方式执行

} catch (IOException e) {

e.printStackTrace();

}

}

91336070f65c77dcb01b97c9c856290a.png

需要注意,在执行shell脚本时,正常这样就可以实现了

a3ba5e037ac98fa8d445281106b700b0.png

但是你会发现你在代码中这样写,会告诉你连接失败,正常写法是 sh /目录下你的shell脚本,这个也是让我纠结了很久,因为像正常的pwd命令他是可以正常执行,但是一旦是其他就不能执行,就必须要使用sh

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值