Python Remote file Download & Transfer to Server (Ubuntu 16)
Remote file Download to Server
Recently, someone asked if they could connect to the server via Python, and I think that’s what they meant.
In Python, we can provide SSH connection to the server and send commands with the module called paramico.
How to Install Paramiko with Python
1 | python -m pip install paramiko |
If Mobile is from the Scripts folder in qpthon pip_cosole.py run script
1 | pip install paramiko |
How to use Paramiko with Python
Then we enter the required information into the following code and send our command. Example of simple Send As command
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | import paramiko # server ip hostname = "xxx.xxx.xxx.xxx" # id myuser = 'root' # pass passwd = '******' # security key if exist mySSHK = '****.pem' sshcon = paramiko.SSHClient() sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy())# no known_hosts error sshcon.connect(hostname, username=myuser, password=passwd) #If you are connected with key, remove the "#" at the beginning of the following line #sshcon.connect(hostname, username=myuser, key_filename=mySSHK) commands = raw_input("Enter the command: ") stdin, stdout, stderr = sshcon.exec_command(commands) recv = stdout.read() print recv sshcon.close() |
Alternatively, if you want to send more than one command at a time, you can use the following code as an example or edit it yourself.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | import paramiko import time # server ip hostname = "xxx.xxx.xxx.xxx" # id myuser = 'root' # pass passwd = '******' # security key if exist. mySSHK = '****.pem' sshcon = paramiko.SSHClient() sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy())# no known_hosts error sshcon.connect(hostname, username=myuser, password=passwd) # If you're connected with the key, remove the "#" sign at the beginning of the following line #sshcon.connect(hostname, username=myuser, key_filename=mySSHK) #You can enter commands to be sent as follows: commands = ''' service --status-all echo "done" date ''' for i in commands.splitlines(): if not i == "": stdin, stdout, stderr = sshcon.exec_command(i) recv = stdout.read() print recv time.sleep(1) sshcon.close() |