Issue
I am trying to log in to the server and give multiple commands from the input file. Here input file is web.txt (contains 'bash', 'df-g' as examples). I am sucessfully able to login to server, but not able to run the commands. I don't know what I am doing wrong here. Can anyone help me please.
import paramiko
web_list = []
def create_web_list():
file = open("web.txt", "r", encoding='utf-8')
for value in file.readlines():
web_list.append(value.strip( ))
return web_list
ip = 'x.x.x.x'
username = 'username'
password = 'password'
def web_device(web_list):
SESSION = paramiko.SSHClient()
SESSION.set_missing_host_key_policy(paramiko.AutoAddPolicy)
SESSION.connect(ip,port=22,username=username,password=password,look_for_keys=False,allow_agent=False)
print("Connection Sucessful")
for cmd in web_list:
stdin,stdout,stderr=SESSION.exec_command(cmd)
outlines=stdout.readlines()
resp=''.join(outlines)
print(resp)
SESSION.close()
if __name__ == "__main__":
web_device(create_web_list())
Solution
Please specify either you want output in one go or you want output for each command separately? if you want with one go then please find below:
Executing multiple commands on paramiko SSHClient, you can place all commands in one line with ;
separator like:
client.exec_command('ls -l; cwd; whoiam')
etc
so please read line from file accordingly and execute commands with one go instead using a loop.
For Individual command execution case use below:
with open("web.txt", "r", encoding='utf-8') as f:
return web_list.append(f.strip( ))
and print output in utf format like '\n'.join(outlines)
Answered By - annonyos Answer Checked By - Katrina (WPSolving Volunteer)