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): 
  paramiko.util.log_to_file("paramiko.log") 
   
  s = paramiko.SSHClient() 
  s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
   
  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. 
   
  print stdout.read() 
   
  s.close() 
   
   
   
def main(): 
   
  hostname = '10.***.***.**' 
  port = 22 
  username = 'root' 
  password = '******' 
  execmd = "free" 
   
  sshclient_execmd(hostname, port, username, password, execmd) 
   
   
if __name__ == "__main__": 
  main() 

Related articles: