简体   繁体   English

如何通过 ssh 执行 Bash 别名

[英]How to execute a Bash alias over ssh

Here's what I'm trying to do:这是我想要做的:

ssh andy@<ip_address> "cat .bash_aliases; sayhello"

Here's what happens:这是发生的事情:

alias sayhello="echo hello"
bash: sayhello: command not found

To be more specific about my problem I'm trying to invoke the command为了更具体地说明我的问题,我正在尝试调用命令
"sudo etherwake -i eth0 <mac_address>" over ssh -- this executes (I think) on my local computer, giving a sudo: unable to resolve host [blabla] error. "sudo etherwake -i eth0 <mac_address>"通过 ssh - 这在我的本地计算机上执行(我认为),给出一个sudo: unable to resolve host [blabla]错误。 It seems like any commands that are not standard bash commands are parsed by my local machine.似乎任何不是标准 bash 命令的命令都由我的本地机器解析。

If that's what's happening, how do I get around it?如果这就是正在发生的事情,我该如何解决? If not, what is the explanation?如果不是,有什么解释?

In general this is not a good idea to use aliases in scripts.一般来说,在脚本中使用别名并不是一个好主意

Yet I can suggest one way to do it, but bare in mind how unsafe it is.然而,我可以建议一种方法来做到这一点,但要记住它是多么不安全。

  • It relies on eval ,它依赖于eval
  • It reads remote files into the shell context.它将远程文件读入 shell 上下文。

Here we go.开始了。

ssh remote_host "shopt -s expand_aliases ; source ~/.bash_aliases ; eval sayhello"

Explanation:解释:

  1. By default alias expansion is enabled only for interactive shells.默认情况下,仅对交互式 shell 启用别名扩展。 To turn it on use shopt -s command.要打开它,请使用shopt -s命令。

  2. You will need to source the aliases into your shell context anyway.无论如何,您都需要将别名输入到您的 shell 上下文中。

  3. Now you are set to use your aliases via the eval command.现在您可以通过eval命令使用您的别名。

Well, it's a pretty messed up hack, but it works:嗯,这是一个非常混乱的黑客,但它有效:

$ ssh xxx.xxx.158.40 'source aliases; alias'

alias emacs='emacs -nw'
alias l.='ls -d .*'
alias ll='ls -l'
alias sayhello='echo hello'
alias vi='vim'
alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'

$ ssh xxx.xxx.158.40 'source aliases; $( alias sayhello | sed -e "s/.$//" -e "s/.*=.//" )'

hello

This also works:这也有效:

ssh xxx.xxx.158.40 "source aliases; \$( alias sayhello | cut -d\' -f2 )"

@ajreal gave a simple solutions in the above comments -- just put what you want to happen in a file, then execute the file. @ajreal 在上面的评论中给出了一个简单的解决方案——只需将你想要发生的事情放在一个文件中,然后执行该文件。

So I created a file on the host called sayhello.sh (containing only the line echo Hello ), then on my local machine used所以我在主机上创建了一个名为sayhello.sh的文件(只包含行echo Hello ),然后在我的本地机器上使用

ssh andy@<ip_address> "sh sayhello.sh"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM