Execute multiple commands in Paramiko so that commands are affected by their predecessors

霸气de小男生 提交于 2019-11-26 04:56:33

问题


I am slowly trying to make a python script to SSH then FTP to do some manual file getting I have to do all the time. I am using Paramiko and the session seems to command, and prints the directory but my change directory command doesn\'t seem to work, it prints the directory I start in

/01/home/

import paramiko

hostname = \'\'
port = 22
username = \'\'
password = \'\'
#selecting PROD instance, changing to data directory, checking directory
command = {
    1:\'ORACLE_SID=PROD\',2:\'cd /01/application/dataload\',3:\'pwd\'
}

ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname,port,username,password)

for key,value in command.items():
    stdin,stdout,stderr=ssh.exec_command(value)
    outlines=stdout.readlines()
    result=\'\'.join(outlines)
    print (result)
ssh.close()

回答1:


Well by accidentally trying something I managed to figure this out I believe. You need to do all the commands at one time and do not need to do them in a loop. for for my instance it would be

import paramiko

hostname = ''
port = 22
username = ''
password = ''
#selecting PROD instance, changing to data directory, checking directory
command = 'ORACLE_SID=PROD;cd /01/application/dataload;pwd'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname,port,username,password)
stdin,stdout,stderr=ssh.exec_command(value)
outlines=stdout.readlines()
result=''.join(outlines)
print (result)
ssh.close()



回答2:


When you run exec_command multiple times, each command is executed in its own "shell". So the previous commands have no effect on an environment of the following commands.

If you need the previous commands to affect the following commands, just use an appropriate syntax of your server shell. Most *nix shells use a semicolon or an double-ampersand (with different semantics) to specify a list of commands. In your case, the ampersand is more appropriate, as it executes following commands, only if previous commands succeed:

stdin,stdout,stderr=ssh.exec_command("ORACLE_SID=PROD && cd /01/application/dataload && pwd")


来源:https://stackoverflow.com/questions/49492621/execute-multiple-commands-in-paramiko-so-that-commands-are-affected-by-their-pre

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!