2016-06-30 6 views
0

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 

これはどのようにすることができますか?

+0

あなたの正しさを評価する場合は、 'pidof process1'が必要です。 – tripleee

+0

私のスクリプト**にログインしているサーバで 'pidof process1' **を実行し、現時点で自分のスクリプト**を持っているサーバではない**と、結果をa文字列 –

答えて

0

read()機能を使用すると、出力全体が表示されます。

result = child.read() 
1

これはあなたを助けるかもしれないと思います。

import subprocess 
import sys 

url="http://www.anyurlulike.any" 
# Ports are handled in ~/.ssh/config since we use OpenSSH 
COMMAND="uname -a" 
ssh = subprocess.Popen(["ssh", "%s" % url, COMMAND], 
        shell=False, 
        stdout=subprocess.PIPE, 
        stderr=subprocess.PIPE) 

result = ssh.stdout.readlines() 
if result == []: 
error = ssh.stderr.readlines() 
print >>sys.stderr, "ERROR: %s" % error 
else: 
print result 
+0

サブプロセス: これは、コマンドを実行するデフォルトのPythonライブラリです。 sshを実行させて、リモートサーバで必要な処理を実行できます。 –

関連する問題