我想自动执行通过ssh (putty)执行的相同操作。在使用putty连接后,我的.bashrc
被加载(因此我可以使用别名)。如果我尝试在Python中这样做,别名sanity
是不可见的:
sanity: command not found
使用source .bashrc
不能解决。
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('xxxxxxx', username='x', password='x', key_filename=None, look_for_keys=False)
stdin, stdout, stderr = ssh.exec_command(
"""
sanity;
""")
stdout.flush()
for line in stdout:
print line
print "END"
print stderr.read()
ssh.close()
因为您正在通过ssh运行命令,所以您没有运行登录shell,因此.bashrc
没有来源。
在这里看到答案:https://superuser.com/questions/306530/run-remote-ssh-command-with-full-login-shell
编辑:尝试在调用exec_command
时设置get_pty=True
否则尝试强制登录shell
exec_command('bash -l -c "sanity;"')
From bash
man page:
当shell不是交互式的时候不扩展别名,除非使用shopt
设置expand_aliases shell选项。
所以如果你想使用别名,你必须先设置expand_aliases
选项
其他提交的解决方案都不适合我。我必须同时使用交互式shell和get_pty。下面的代码可以在Ubuntu上运行和测试:
source_bashrc = True # switch this flag to revert to 'normal' execution
command_to_execute = 'll'
if source_bashrc:
command_to_execute = f'bash -ic "{command_to_execute}"'
client.exec_command(command_to_execute, get_pty=source_bashrc)
-i标志创建一个交互式终端,它是bashrc的源。我从这个链接得到了提示。