java 接收命令行 密码,从字符串中获取命令(密码)并将其设置为InputStream到Java(JSCH)中的Unix服务器...

Almost similar to this topic, but here I am not a superuser to use --stdin.

So I found an other way round, I would open a "shell" in background and give input to shell via a String through InputStream

I made a code like below:

String s = "cd bin\n";

byte bb[] = s.getBytes();

InputStream intt = new ByteArrayInputStream(bb);

channel.setInputStream(new FilterInputStream(intt) {

public int read(byte[] b, int off, int len) throws IOException {

return in.read(b, off, (len > 1024 ? 1024 : len));

}

});

Now this works perfectly when I want to execute only one command but I want to give multiple commands, for which I am facing issue.

Any suggestions?

Regards,

Ishan

解决方案

I found a solution to question I asked, don't know if its a full proof solution since I tested with limited period of time and I did it beast way I can.

channel = session.openChannel("exec");

((ChannelExec) channel).setCommand(command);

((ChannelExec) channel).setPty(true);

In the command string

String command = "(echo old_password; echo new_password; echo new_password) | passwd username";

or if not a superuser then,

String command = "(echo old_password; echo new_password; echo new_password) | passwd"

That is it ;)

regards,

icr

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
昨天一个网友问如何能够将输入密码的工作在shell里面自动完成,研究了一下,发现这种交互式的工作,普通的shell实现不了,据说可以借助expect来搞定,所以初步学习了一下expect,成果和大家分享一下: 应用一: 实现从普通用户“test”切换到root用户,自动输入root的密码,不用在终端提示符下执行密码输入操作。 步骤: (1)vi autosu.sh (2)#! /usr/bin/expect -f //指定expect工具的路径,如果不清楚具体路径,可以用"which expect"命令来查看。 spawn su - // 在expect 用"spawn"关键字来调用命令“su - ” expect ":" //在执行了su - 命令之后,提示输入密码的提示符。例如你在执行了su - 命令之后,终端里面会出现提示“口令:”,那么你就可以在这里写expect ":",或者expect -exact "口令:" send "rootpasswd\r" //这里expect用send将你的root密码自动输入到上面的提示符之后。 interact //操作完成。 注意:这里强调一下执行脚本时要注意的地方,不能按照习惯来用sh ***.sh来这行expect的程序,会提示找不到命令,因为expect用的不是bash所以会报错。执行的时候直接./***.sh就可以了。~切记! 应用二: 从普通用户切换到root之后,执行“ls”操作,调用执行aaa.sh,返回执行结果,间隔10S。 #/usr/bin/expect -f spawn su - // 在expect 用"spawn"关键字来调用命令“su - ” expect ":" //在执行了su - 命令之后,提示输入密码的提示符。例如你在执行了su - 命令之后,终端里面会出现提示“口令:”,那么你就可以在这里写expect ":",或者expect -exact "口令:" send "rootpasswd\r" //这里expect用send将你的root密码自动输入到上面的提示符之后。 expect "#" //当遇到提示符以#结尾时,即为root权限时; send "ls\r" //expect 用spend方法调用ls 命令,并且回车(“\r”) expect "#" send "sh aaa.sh\r" //调用sh aaa.sh,即执行一个脚本文件aaa.sh。 expect "#" send "echo $?\r" sleep 10 interact

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值