Paramiko将列出SAS Jobs(PYTHON)

时间:2017-11-01 17:12:24

标签: python ssh paramiko

早上好。所以我在工作中坚持这个问题。使用Paramiko库我试图自动执行许多人为DB2实例工作的简单任务。我已经设置了一个工作来重置一堆密码,所以我知道连接到服务器的基本知识是正确的,这只是这些命令没有做我想要的事情。我试图做的是在" bjob​​s"的第二个命令之后。我希望能够查看输出。我尝试过使用stdout.read(),到目前为止它没有给我任何东西,只有b''。非常需要任何帮助。

from paramiko import client
from os import getlogin

class ssh:
client = None

def __init__(self, address, username, password):
    print("Connecting to server")
    self.client = client.SSHClient()
    self.client.set_missing_host_key_policy(client.AutoAddPolicy())
    self.client.connect(address, username=username, password=password)
    print("Connected to " + address)

def sendCommand(self, command):
    if(self.client):
        stdin, stdout, stderr = self.client.exec_command(command)
        x= stdout.read()
        print(x)
        while not stdout.channel.exit_status_ready():
            if stdout.channel.recv_ready():
                alldata = stdout.channel.recv(1024)
                while stdout.channel.recv_ready():
                    alldata+=stdout.channel.recv(1024)
                print(str(alldata, 'utf8'))
    else:
        print("connection not opened")


serverCon = "My Server"
plist = []
currPass = 'MyPassword!'

#get user information
userName = getlogin()

#Connect to server, insert and chnage passwords

connection = ssh(serverCon, userName, currPass)
connection.sendCommand(r'. /opt/sas/lsf/conf/profile.lsf')

connection.sendCommand('bjobs')

1 个答案:

答案 0 :(得分:1)

每个exec_command()都会使用新的shell实例(ssh服务器上的用户登录shell )执行命令,因此您的第一个. /opt/sas/lsf/conf/profile.lsf不会影响以下bjobs。你应该写

exec_command('. /opt/sas/lsf/conf/profile.lsf; bjobs')

基本相同
ssh user@host '. /opt/sas/lsf/conf/profile.lsf; bjobs'

根据手册:

  

class paramiko.client.SSHClient

     
    

exec_command(command, bufsize=-1, timeout=None, get_pty=False)

         

在SSH服务器上执行命令。 打开新频道,执行请求的命令。命令的输入和输出流作为Python文件类对象返回     stdin,stdout和stderr。

  
     

class paramiko.channel.Channel

     
    

exec_command(*args, **kwds)

         

在服务器上执行命令。如果服务器允许,则通道将直接连接到     stdin,stdout和正在执行的命令的stderr。     当命令执行完毕后,该频道将被关闭,无法重复使用。如果要执行其他命令,则必须打开新频道。