2

私は、実行時にサーバーに ssh 接続して一連のコマンドを実行する、expect スクリプトを作成しました。擬似コードは次のようになります。

#!/usr/bin/expect
spawn ssh usr@myip
expect "password:"
send "mypassword\n";
send "./mycommand1\r"
send "./mycommand2\r"
interact

bash シェル ($ ./myscript.txt) から実行すると、コードは正常に実行されます。私が今やりたいことは、bash シェルと同じ方法でスクリプト内のコマンドを実行する行を Python ファイルに含めることです。擬似コードは次のようになります。

import subprocess
def runmyscript():
    subprocess.call("myscript.txt", executable="expect", shell=True)
def main():
    run = runmyscript():
if __name__ == '__main__': main()   

myscript.txt スクリプト ファイルを runmyscript.py ファイルと同じディレクトリに配置しましたが、python ファイルを実行すると次のエラーが表示されます。

WindowsError: [Error 2] The system cannot find the file specified

python.org サイトのドキュメントを読みましたが、役に立ちませんでした。.py コード内から bash スクリプトを実行するための狡猾なソリューションを持っている人はいますか?

解決策:このコードは私にとってはうまくいきます。

child = subprocess.Popen(['bash', '-c', './myscript.txt'], stdout = subprocess.PIPE)

このコードを使用して、Expect ファイルを ssh に呼び出し、コマンドを .py ファイルからサーバーに送信しました。マシンに pycrypto/paramiko をビルドする際に問題がある場合に役立ちます。

4

2 に答える 2

3

これがあなたのexpectスクリプトのPython実装です:

import paramiko

user = "user"
pass = "pass"
host = "host"

client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, port=22, username=user, password=pass)
client.exec_command("./mycommand1")
client.exec_command("./mycommand2")
client.close()
于 2012-06-21T22:46:04.603 に答える
1

pexpect を使用できます ( http://www.noah.org/wiki/pexpect )

これは、ssh を介してリモートでコマンドを実行するときに遭遇する可能性のある非常に多くのケースを処理する関数の例です。

import pexpect 

## Cleanly handle a variety of scenarios that can occur when ssh or scp-ing to an ip:port
# amongst them are:
# 
# (1) key has not been setup
# (2) key has changed since last time
# (3) command was executed (check exit status and output) 
#
# @param cmdLine  The "scp" or "ssh" command-line
# @param mtimeout The millisecond timeout to wait for the child process to return
# @param log      The log to record events to if necessary
def cleanlyHandleSecureCmd(cmdLine, mtimeout = None, log = None):
  status = -1
  output = None

  if mtimeout == None:
    mtimeout = 60 * 1000

  if cmdLine != None and ('scp' in cmdLine or 'ssh' in cmdLine):
    # Scenarios for ssh include: (1) key not setup (2) key changed (3) remote cmd was executed (check exit status)
    scenarios = ['Are you sure you want to continue connecting', '@@@@@@@@@@@@', EOF]
    child     = spawn(cmdLine, timeout = mtimeout)
    scenario  = child.expect(scenarios)

    if scenario == 0:
      # (1) key not setup ==> say 'yes' and allow child process to continue
      child.sendline('yes')

      scenario = child.expect(scenarios)

    if scenario == 1:
      if log != None:
        # (2) key changed ==> warn the user in the log that this was encountered
        log.write('WARNING (' + cmdLine  + '): ssh command encountered man-in-the-middle scenario! Please investigate.')

      lines    = child.readlines()
      scenario = child.expect([EOF])

      child.close()
    else:
      # (3) remote cmd was executed ==> check the exit status and log any errors
      child.close()

      status = child.exitstatus
      output = child.before
      output = sub('\r\n', '\n', output)  # Do not be pedantic about end-of-line chars 
      output = sub('\n$',  '',   output)  # Ignore any trailing newline that is present

      if status == None:
        status = child.status

      if status != 0 and log != None:
        log.error('Error executing command \'' + str(cmdLine) + '\' gave status of ' + str(status) + ' and output: ' + str(output))
  else:
    if log != None:
      log.error('Command-line must contain either ssh or scp: ' + str(cmdLine))

  return (status, output)
于 2012-06-22T16:15:08.913 に答える