Download file from a URL into a remote machine - python

I am looking at downloading a file from URL into remote machine directly.. Is this possible with python paramiko sftp?

You can copy the download script first to the remote machine and the execute it
Example:
import paramiko
host="hostname"
user="username"
#SSH Connection#
ssh = paramiko.SSHClient()
ssh.load_host_keys()
ssh.connect(host, username=user, password='password')
#Copy Script to Remote#
sftp = ssh.open_sftp()
sftp.put("localpath", "remotepath")
sftp.close()
#Close#
stdin, stdout, stderr = ssh.exec_command("python " + "remotepath" + '/downloadfile.py')
print "stderr: ", stderr.readlines()
print "pwd: ", stdout.readlines()
or you can call the wget command directly instead of using the download script.
Example:
import paramiko
host="hostname"
user="username"
#SSH Connection#
ssh = paramiko.SSHClient()
ssh.load_host_keys()
ssh.connect(host, username=user, password="password")
stdin, stdout, stderr = ssh.exec_command("cd download_folder; wget http://DOWNLOAD.URL")
print "stderr: ", stderr.readlines()
print "pwd: ", stdout.readlines()

Related

Read command output in Paramiko without prompts and other shell output

I'm trying to send an output of a specific command to a txt file,
file = 'output_from_the_server.txt'
def connect(host):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=host, port=port, username=username, password=password, look_for_keys=False, allow_agent=False)
ssh = client.invoke_shell()
return ssh
def test(server_host):
print(server_host)
IP = server_view(server_host)
print(IP)
ssh = connect(IP)
time.sleep(2)
ssh.send('clear -x && [command]\n')
time.sleep(3)
resp = ssh.recv(655353)
output = resp.decode('ascii').split(',')
output = ''.join(output)
ssh.close()
with open(file, 'w') as f:
for i in output:
f.write(i)
f.close()
The file include all of the outputs before the command, even i tried to use clear screen.
You are starting a shell, so naturally you get all the output you would get in the shell, including all prompts and banners.
Do not use shell to automate command execution, use the "exec" SSH channel.
stdin, stdout, stderr = client.exec_command(command)
stdout.channel.set_combine_stderr(True)
output = stdout.readlines()
See Paramiko: read from standard output of remotely executed command.
Related question:
Is there a simple way to get rid of junk values that come when you SSH using Python's Paramiko library and fetch output from CLI of a remote machine?
Obligatory warning: Do not use AutoAddPolicy on its own – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".
Here's an example of executing a command through a paramiko.
Sending the output to a file should then be easy.
def ssh_command(ip, user, command):
key = paramiko.RSAKey.from_private_key_file(os.getenv('HOME') + '/.ssh/paramiko')
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ip, username=user, pkey=key)
ssh_session = client.get_transport().open_session()
if ssh_session.active:
ssh_session.exec_command(command)
out = []
r = ssh_session.recv(1024).decode('utf-8')
while r:
out.append(r)
r = ssh_session.recv(1024).decode('utf-8')
return ''.join(out)
return ''
res = ssh_command('127.0.0.1', 'user', 'cd / ; ls */ | xargs ls')
for outputin str(res).split('\\n'):
print(output)
Don't forget to generate a key with ssh-keygen.

Perform unix operations after connecting to remote host using ssh

Using paramiko to connect to remote host. How do i move across directories and perform unix operations? Sample code below
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('remote ip', username='username', password='password')
ftp = ssh.open_sftp()
ssh.exec_command('cd /folder1/folder2')
How do i perform operations like listing files in a directory, checking current working directory and perform other unix commands?
This way (example on ls command):
import paramiko
import sys
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('x.x.x.x', port=22, username='user', password='pass')
stdin, stdout, stderr = ssh.exec_command('ls')
# Wait for the command to terminate
while not stdout.channel.exit_status_ready():
# Only print data if there is data to read in the channel
if stdout.channel.recv_ready():
rl, wl, xl = select.select([stdout.channel], [], [], 0.0)
if len(rl) > 0:
# Print data from stdout
print stdout.channel.recv(1024),
ssh.close()

How do I take screenshot on Unix using python script on windows PC?

Am trying to take a screenshot of UNIX server from my Windows PC. My command is not working it seems. When I try the same command on terminal it saves the file, however it is not with my below code.
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(sftp_server, username=sftp_login, password=sftp_password)
stdin, stdout, stderr = ssh.exec_command("xwd -root | convert xwd:- screenshot22.jpg")
sftp = ssh.open_sftp()
transport = paramiko.Transport((sftp_server, sftp_port))
transport.connect(username = sftp_login, password = sftp_password)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.get("screenshot22.jpg", 'screenshot22.jpg', None)
sftp.close()
ssh.close()
Note:
1. xwd is installed on my UNIX Server.
2. Tried Import command, but that takes (2nd desktop of UNIX, not the one am trying to)
With the help of #Christopher Apple, I have figured out a way.
The working source code is,
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(sftp_server, username=sftp_login, password=sftp_password)
stdin, stdout, stderr = ssh.exec_command("xwd -out screenshot.xwd -root -display :0.0")
stdin, stdout, stderr = ssh.exec_command("convert screenshot.xwd screenshot22.jpg")
sftp = ssh.open_sftp()
transport = paramiko.Transport((sftp_server, sftp_port))
transport.connect(username = sftp_login, password = sftp_password)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.get("screenshot22.jpg", 'screenshot22.jpg', None)
sftp.close()
ssh.close()

Python Code to get the files from remote host using Paramiko

import paramiko
paramiko.util.log_to_file(r'D:\logs\paramico.log')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('xxx.xxx.xx.xx', port=22, username='xxxxx', password='xxxxxx')
stdin, stdout, stderr = ssh.exec_command('ll')
output = stdout.readlines()
print '\n'.join(output)
print output
This is a linux host and I want to list the files/folders present in it. But, I am getting empty list [].
Can please any one suggest me how to proceed to list the contents present in that.
import paramiko
paramiko.util.log_to_file(r'D:\logs\paramico.log')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('xxx.xxx.xx.xx', port=22, username='xxxxx', password='xxxxxx')
stdin, stdout, stderr = ssh.exec_command('ls -al')
output = stdout.readlines()
output1 = stderr.readlines()
print '\n'.join(output)
print output
print output1
As my host has hidden files, I need to use ls -al

Python ssh command to change user

I need to run a python script that will ssh to a remote host. The first command to run on this remote host is "sudo su". I have the password for it. Then I need to cd to a directory and copy a file to my local box. I tried in two ways. Both of them don't work.
script #1:
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostName,username='e0258595',password='<password>')
stdin,stdout,stderr = ssh.exec_command("sudo su; whoami")
stdin.write('password\n')
stdin.flush()
data = stdout.readlines()
for line in data:
print line
The output is still e0258595.
Script #2:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostName, username="e0258595", password="<password>")
transport = ssh.get_transport()
session = transport.open_session()
session.set_combine_stderr(True)
session.get_pty()
#for testing purposes we want to force sudo to always to ask for password. because of that we use "-k" key
session.exec_command("sudo su; whoami")
stdin = session.makefile('wb', -1)
stdout = session.makefile('rb', -1)
#you have to check if you really need to send password here
stdin.write("<password>"+'\n')
stdin.flush()
data = stdout.readlines()
for line in data:
print line
This one just hang.
What is the problem?
Have you tried using get_pty=True?
stdin,stdout,stderr = ssh.exec_command("sudo su; whoami", get_pty=True)

Categories