pexpect
を使用してログインしたリモートサーバでコマンドを実行し、その結果を変数に文字列形式で格納する方法?リモートサーバでコマンドを実行し、結果をPythonスクリプトの文字列変数に保存
私は次のようにサーバへの接続をした:
COMMAND_PROMPT = '[#$] '
TERMINAL_PROMPT = '(?i)terminal type\?'
TERMINAL_TYPE = 'vt100'
SSH_NEWKEY = '(?i)are you sure you want to continue connecting'
child = pexpect.spawn('ssh -l %s %s'%(loginuser, servername))
i = child.expect([pexpect.TIMEOUT, SSH_NEWKEY, COMMAND_PROMPT, '(?i)password'])
if i == 0: # Timeout
print('ERROR! could not login with SSH. Here is what SSH said:')
print(child.before, child.after)
print(str(child))
sys.exit (1)
if i == 1: # In this case SSH does not have the public key cached.
child.sendline ('yes')
child.expect ('(?i)password')
if i == 2:
# If a public key was setup to automatically login
pass
if i == 3:
child.sendline(password)
# Now we are either at the command prompt or
# the login process is asking for our terminal type.
i = child.expect ([COMMAND_PROMPT, TERMINAL_PROMPT])
if i == 1:
child.sendline (TERMINAL_TYPE)
child.expect (COMMAND_PROMPT)
今、私はにログインして、サーバー上で次のコマンドを実行するとしますと、私のPythonスクリプト内の文字列に結果を保存しますそれ自身:
ps -ef|grep process1
これはどのようにすることができますか?
あなたの正しさを評価する場合は、 'pidof process1'が必要です。 – tripleee
私のスクリプト**にログインしているサーバで 'pidof process1' **を実行し、現時点で自分のスクリプト**を持っているサーバではない**と、結果をa文字列 –