2

サーバーにsshでログインし、「suユーザー名」(パスワードなし)を実行して、そのユーザー(sshに直接ログインしていない)としていくつかのコマンドを実行する必要があります。

ターミナルからは次のようになります。

root@cs01:~# su foo
foo@cs01:/root$ cd
foo@cs01:~$ ls

私はparamiko(python)でこれをやろうとしました:

import paramiko
ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect('host', username='root', password='mypassword', key_filename='<filename>')

stdin, stdout, stderr = ssh.exec_command('su foo')
print stdout.readlines()
stdin, stdout, stderr = ssh.exec_command('cd')
print stdout.readlines()
stdin, stdout, stderr = ssh.exec_command('pwd')
print stdout.readlines()
ssh.close()

しかし、スクリプトは終了しません。

ログは次のとおりです。

...
DEB [20111207-16:22:25.538] thr=1   paramiko.transport: userauth is OK
INF [20111207-16:22:25.921] thr=1   paramiko.transport: Authentication (publickey) successful!
DEB [20111207-16:22:25.923] thr=2   paramiko.transport: [chan 1] Max packet in: 34816 bytes
DEB [20111207-16:22:26.088] thr=1   paramiko.transport: [chan 1] Max packet out: 32768 bytes
INF [20111207-16:22:26.088] thr=1   paramiko.transport: Secsh channel 1 opened.
DEB [20111207-16:22:26.151] thr=1   paramiko.transport: [chan 1] Sesch channel 1 request ok

これだけを試してみると:

stdin, stdout, stderr = ssh.exec_command('su foo')
#without print
stdin, stdout, stderr = ssh.exec_command('pwd')
print stdout.readlines()

foo としてではなく、root として pwd を実行します。

どうしたの?

4

1 に答える 1

8

exec_command()呼び出しは新しいシェルで行われるため、前のコマンドから引き継がれた状態はありません。コマンドの実行が前のコマンドに依存している場合は、コマンドを1つのステートメントで送信するか、スクリプトとして送信する必要があります。インタラクティブシェルがinvoke_shell必要な場合は、コマンドがありますが、シェル出力を解析してインタラクティブな使用をシミュレートする必要があります(pexpectライブラリはここで使用できます)。

sudoコマンドを使用するか、コマンドsu -cを実行できます。ただし、必要なユーザーの安全なログインを構成し、そのユーザーとして直接接続することをお勧めします。

于 2011-12-07T15:57:07.117 に答える