expected_remote_run.py
expected_remote_run.py
import subprocess
def remote_execute(host_ip, host_passwd, cmd, user='test'):
private_key_file = '/tmp/id_rsa'
private_key_pass = '******'
cmd = cmd.replace('"', r'\\\"')
cmd = cmd.replace("'", r"'\''")
ssh_cmd = r"""
expect -c '
spawn ssh -i {private_key_file} \
-o "StrictHostKeyChecking no" \
-o "UserKnownHostsFile /dev/null" \
-o "ConnectTimeout 20" {user}@{ip} "su - root -c \"{cmd}\" ";
set timeout 20;
expect "Enter passphrase";
send {private_key_pass}\r;
expect Password;
send {password}\r;
expect eof;
catch wait result;
exit [lindex $result 3]
'""".format(private_key_file=private_key_file,
ip=host_ip, private_key_pass=private_key_pass,
password=host_passwd,
user=user, cmd=cmd)
print('ssh_cmd: [%s]' % ssh_cmd)
ssh_fd = subprocess.Popen(
ssh_cmd, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, stdin=subprocess.PIPE)
stdout, stderr = ssh_fd.communicate(input=host_passwd)
status = ssh_fd.returncode
split_token = "Password: %s" % host_passwd
if split_token not in stdout:
return 1, stdout
msg = stdout.split(split_token)[1].strip()
msg = msg.replace("\r\n", "\n")
return status, msg
host_ip = '1.1.1.1'
root_passwd = '******'
cmd = """python -c 'print("hi")' """
err, output = remote_execute(host_ip, root_passwd, cmd)
print('retcode: %s' % err)
print('===========')
print(output)
print('===========')