Realization of python su to root account

Simply record how automatic su linux system through python code - to switch to the root account,

To use modules: paramiko

Using the method: invoke_shell functions: creating an interactive shell at the end of the SSH server and the pseudo terminal may be configured according to their needs, can () function to add parameters in invoke_shell.

Test code is as follows:

paramiko Import 

ssh_client = paramiko.SSHClient () 
ssh_client.set_missing_host_key_policy (paramiko.AutoAddPolicy ()) 
ssh_client.connect (= ipaddr hostname, Port = Port, User = username, password = pwd) 
# assume more normal user login 


chan = ssh_client. invoke_shell () # using the pseudo-terminal, to create a default interactive vt100 
chan.send ( 'su - \ n' ) # su command sent 
chan.recv (4096) .decode () # receive a return 
chan.send ( 'root password \ n ') transmits the root password # 
# more complete handover root 

# execute shell commands start 
stdin, stdout, stderr = self.client.exec_command (' LS / root ') 
OUT, ERR = stdout.read (), stderr.read () 
Mess OUT OUT IF the else ERR = 
Mess = mess.strip (). decode () 
Print (Mess) # View output

  

Guess you like

Origin www.cnblogs.com/zy6103/p/10963366.html