大网数据广告活动
服务器运维问答

Issue with the combination of ssh, bash --login and exec

· 52CE 我爱测

Here are few situations I'm in. foo is the ssh server to which password less login is set up. $ ssh foo $ bash --login -c 'exec $0 "$@"' ls -lrt It's working as expected. ssh foo bash --login -c ls -lrt This is not working as exp…

问题原文

原帖链接 · RatDon · CC BY-SA 3.0

Here are few situations I'm in. foo is the ssh server to which password less login is set up.

$ ssh foo
$ bash --login -c 'exec $0 "$@"' ls -lrt

It's working as expected.

ssh foo bash --login -c ls -lrt

This is not working as expected. Only ls is working ignoring the -lrt parameter.

And my requirement is to run the 1st example with ssh like

ssh foo bash --login -c 'exec $0 "$@"' ls -lrt

I know I've problems from the 2nd example itself. But I was just trying something to make it work and to find where the problem is. The 3rd example is not showing any error/output at all.

How do I proceed to achieve the 3rd example?

已采纳解答

原帖链接 · Tollef Fog Heen · CC BY-SA 3.0

You can do ssh foo bash --login -c '"exec \$0 \$@"' ls -lrt.

To find out what actually happens, strace is your friend.

ssh foo strace -vff -e execve bash --login -c 'exec $0 "$@"' ls -lrt gives me something like:

execve("/bin/bash", ["bash", "--login", "-c", "exec", "zsh", "ls", "-lrt"], [LANG=…]

My shell is zsh, which should give you a hint to what's happening here: That $0 is interpreted by the shell spawned to parse the command line sent over the SSH command. If we just escape the $0 and "$@" parts like: ssh foo strace -vff -e execve bash --login -c 'exec \$0 "\$@"' ls -lrt we get:

execve("/bin/bash", ["bash", "--login", "-c", "exec", "$0", "$@", "ls", "-lrt"], ["LANG=... As you can see here, bash is called with the arguments --login, -c, exec, $0 and so on. This doesn't get us all the way to where we want to be, since it's now effectively just calling exec by itself. To work around this, we need to quote what comes after the -c argument so it's not unpacked too early, like ssh foo strace -vff -e execve bash --login -c '"exec \$0 \$@"' ls -lrt:

execve("/bin/bash", ["bash", "--login", "-c", "exec $0 $@", "ls", "-lrt"], ["LANG=…

This is accepted by bash, since it allows you to use $@, but if you're writing proper POSIX sh, you should use "$@", in which case the right answer is ssh foo strace -vff -e execve bash --login -c '"exec \$0 \"\$@\""' ls -lrt:

execve("/bin/bash", ["bash", "--login", "-c", "exec $0 \"$@\"", "ls", "-lrt"], ["LANG=…

I assume you're using ls -lrt as a proxy for some other more complex command that actually needs bash --login and such, else just do what suggested in the first comment and use ssh foo 'ls -lrt' instead.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-06-02)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。