收录日期:2019/04/18 21:08:20 时间:2010-06-22 20:38:58 标签:python

I am trying to connect to the server via ssh and dump the "df- h" output in some text file.

p=pexpect.spawn('ssh some.some.com')

i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==0:
    print "I say yes"
    p.sendline('yes')
    i=p.expect([ssh_newkey,'password:',pexpect.EOF])
if i==1:
    p.sendline("somesome")
    p.expect(pexpect.EOF)
    i = p.sendline('df -h > /home/test/output.txt')
    print i
    response = p.before
    print response

print p.before

I am trying to connect to the server and dump the server data in some text file. My problem is i = p.sendline('df -h > /home/test/output.txt') is not doing anything, Basically my output file is empty. Please help me out.

Thanks.

You probably want to use paramiko to manage operations over an SSH connection.

My problem is i = p.sendline('df -h > /home/test/output.txt') is not doing anything

Isn't it setting i to 29? Is that what you mean?

Basically my output file is empty.

How do you know that? Nothing in this code is checking whether that file exists on the remote machine.

Please help me out.

Does your user on the remote machine have permission to write to the /home/test directory there, indeed, does that directory even exist? You're really giving us too few hints at exactly what you're doing, in exactly what context, and what exactly happens as a result, to be of any help yet, except for peppering you with such questions hoping you'll eventually tell us the many crucial pieces of data you're simply omitting. Help us help you out!-)

If you find yourself doing a lot of work over ssh to the same machines then you may want to look into something like func.

It looks like you're using Python as a shell here. Why don't you just save the relevant commands in a bash file and run that in one command instead? I think that'd work out a lot better. I also recommend that you enable SSH publickey authentication, it works better than passwords. Use the subprocess module to spawn processes from inside Python.

I guess this advice isn't helpful if you actually need to do things this way for some reason.