Python implements SSH remote login and executes the command method of share

  • 2020-05-30 20:33:40
  • OfStack

In the automation test process, the more common operation is to operate on the remote host, how to operate? Log in to the host remotely using SSH and then execute command.

Using Python to do this is fairly straightforward. Here's the test code.

The code is as follows: (code running environment: python27+eclipse+pydev)

import paramiko 
def sshclient_execmd(hostname, port, username, password, execmd): 
  s = paramiko.SSHClient() 
  s.connect(hostname=hostname, port=port, username=username, password=password) 
  stdin, stdout, stderr = s.exec_command (execmd) 
  stdin.write("Y") # Generally speaking, the first connection, need a simple interaction. 
def main(): 
  hostname = '10.***.***.**' 
  port = 22 
  username = 'root' 
  password = '******' 
  execmd = "free" 
  sshclient_execmd(hostname, port, username, password, execmd) 
if __name__ == "__main__": 

Related articles: