21

Java ssh 客户端 Jsch 怎么执行 sudo su 后再执行新命令

 2 years ago
source link: https://www.v2ex.com/t/844182
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  程序员

Java ssh 客户端 Jsch 怎么执行 sudo su 后再执行新命令

  leiuu · 5 小时 59 分钟前 · 279 次点击

背景是这样的。

我在本地通过 jsch 对一台远程机器执行命令,但该命令需 sudo 权限。

远程用户,只开放了登录用户的 sudo su 的权限。

导致想执行 sudo 命令需分两步:

sudo su -
docker ps

这里涉及到 session 切换,原生的 Jsch 的 ExecChannel 就用不了。

改为 ChannelShell 。

ChannelShell channel = (ChannelShell) session.openChannel("shell");

OutputStream os = channel.getOutputStream();

os.write(("sudo su - \r").getBytes());
os.flush();
os.write(("docker ps \r").getBytes());
os.flush();
os.write(("exit \r".getBytes());
os.flush();
os.write(("exit \r").getBytes());
os.flush();

但这个命令的返回,是一堆 shell 命令和结果糅合在一起,比较难提取真正的结果。

sudo su -
docker ps
exit
exit
20:51:19  [email protected]:~ 

$ sudo su -
20:51:19  [email protected]:~ 

# docker ps
CONTAINER ID   IMAGE                                                COMMAND                  CREATED        STATUS        PORTS     NAMES
2a3da88c5f8b   ca6e5bfba5a5                                         "/usr/bin/tini -- /u…"   3 days ago     Up 3 days               docker_job_xxx
20:51:19  [email protected]:~ 

# exit
logout
20:51:19  [email protected]:~ 

$ exit
logout

而且如果远程机器换一个 os ,例如是 centos ,则:

Last login: Thu Mar 31 20:27:32 2022 from 192.168.1.2

sudo su -
docker ps
exit
exit
[[email protected] ~]$ sudo su -
Last login: Thu Mar 31 14:17:40 CST 2022 on pts/3
[[email protected] ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
8929e8f93280        img_xxx     "/usr/sbin/init"    5 months ago        Up 5 months                             docker_job_yyy
[[email protected] ~]# exit
logout
[[email protected] ~]$ exit
logout

不同系统或者 terminal 可能会返回格式不同,导致真正想要的结果难以提取。

请教是否有好的解决方法呢?

http://www.jcraft.com/jsch/


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK