アクセスをsubprocess.Popen
ラップする場合はうまくいくかもしれませんがssh
、これは推奨される方法ではありません。
paramikoの使用をお勧めします。
import paramiko
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(server, username=user,password=password)
...
ssh_client.close()
また、ユーザーが入力しているかのように端末をシミュレートする場合は、次のようにします。
chan=self.ssh_client.invoke_shell()
def exec_cmd(cmd):
"""Gets ssh command(s), execute them, and returns the output"""
prompt='bash $' # the command line prompt in the ssh terminal
buff=''
chan.send(str(cmd)+'\n')
while not chan.recv_ready():
time.sleep(1)
while not buff.endswith(prompt):
buff+=self.chan.recv(1024)
return buff[:len(prompt)]
使用例:exec_cmd('pwd')
事前にプロンプトがわからない場合は、次のように設定できます。
chan.send('PS1="python-ssh:"\n')