Reputation: 167
I am using Python 2.7.6 and Paramiko module (on a Linux server) to connect to a Windows server and send some commands and get output. I have a connect function which takes IP, username and password of the remote Windows server and I get an sshobj when that happens. How do I use it to send remote calls is my question?
If it were a local system, I would just say "os.system" but not sure about the remote calls. Can someone help?
My code looks like below: sys.path.append("/home/me/code")
import libs.ssh_connect as ssh
ssh_obj = ssh.new_conn(IP, username, password)
stdin, stdout, stderr = ssh_obj.exec_command("dir") #since the remote system I am SSHing into is Windows.
my "new_conn" looks like this:
import paramiko
def new_conn(IP, username, password):
ssh_obj = paramiko.SSHClient()
ssh_conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_conn.connect(IP, username, password), timeout=30)
return ssh_obj
All I get from stdin, stdout and stderror is "active; 1 open channel anhd some bunch of info like ChannelFile, aes, etc..).
I was hoping to see the output of "dir" from Windows on my Linux..
tried "stdout.read()" and "stdout.readlines()" but the former came out with "stdout" and the latter came out with "[]"!
Thanks!
Upvotes: 3
Views: 13190
Reputation: 1496
I installed FreeSSHd on my Windows, and it works!
FreeSSHd Tutorial: (Chinese) https://jingyan.baidu.com/article/f7ff0bfc1ebd322e27bb1344.html
Code:(Python 3)
import paramiko
hostname = "windows-hostname"
username = "windows-username"
password = "windows-password"
cmd = 'ifconfig'
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname,username=username,password=password)
print("Connected to %s" % hostname)
except paramiko.AuthenticationException:
print("Failed to connect to %s due to wrong username/password" %hostname)
exit(1)
except Exception as e:
print(e.message)
exit(2)
try:
stdin, stdout, stderr = ssh.exec_command(cmd)
except Exception as e:
print(e.message)
err = ''.join(stderr.readlines())
out = ''.join(stdout.readlines())
final_output = str(out)+str(err)
print(final_output)
Upvotes: 2
Reputation: 651
You need to add cmd.exe /c
before dir
as cmd.exe /c dir
to be able to run commands remotely on Windows.
Stick to exec_command and do not try send/recv commands. I never got send/recv commands to work with Windows, at least with the SSH server I am using with windows (FreeSSHd).
Upvotes: 1