I found a small script that can select data in the explorere to upload it using PyAutoIt. The script looks like this:
autoit.win_active("Open")
sleep(2)
autoit.control_send("Open","Edit1",data_path)
sleep(1.5)
autoit.control_send("Open","Edit1","{ENTER}")
I want to do the same thing, but from my Debian GNU/Linux SSH server. The problem is that PyAutoIt only works for windows. Are there any well documented alternatives out there that I could use to preform the same actions?
You could use native python and scp
import subprocess
# Use subprocess to run 'scp' take FILE and pass it to the ssh host
subprocess.run(["scp", FILE, "USER#SERVER:PATH"])
#e.g. subprocess.run(["scp", "somefile.txt", "john#doe.org:/path/to/somefile.txt"])
Note that you have to generate an ssh key so that scp automatically gets authenticated - that way you will not be asked to provide the password.
Alternatively you could probably do (I have not tested this)
import subprocess
# Use subprocess to run 'scp' take FILE and pass it to the ssh host
subprocess.run(["scp", FILE, "USER:PASSWORD#SERVER:PATH"])
#e.g. subprocess.run(["scp", "somefile.txt", "john:secretpassword#<IPADDRESSorDNSNAME>:/path/to/somefile.txt"])
Related
Your manager just asked you to find out what is the hostname (/etc/hostname) and if there are any files in the www directory. Your manager wants you to check this on two Ubuntu-based machines. However, they want you to have this written in a way that will scale to all 100 servers on the network. Achieve the following items:
Make a Flowchart.
Create Pseudocode.
Make a single SSH connection via paramiko and send a command to check the hostname and a second command to see if there is anything in the www directory.
Input the IP addresses from a file (text or CSV).
Save the output of both commands, make sure to note what IP the data came from, to a file (text or CSV).
As mirlinda said, this is a set of requirement rather than a question. I just have a plan for your information.
You can write all ip address to text file with one ip per line.
Use ssh-keygen -t rsa -C "your mail" command to create ssh rsa key in your 100 servers.
Run ssh-copy-id -i ~/.ssh/id_rsa.pub root#[ip] to make your administrator machine can access which server you want to access without password.
Write a python script to read one ip per time from the text file saved your all server ip by readline interface.
And use check_output interface to run hostname command to get server host name and ls [full path of www] to get contents of www directory.
You just can save return contents of check_output interface to a file by redirection symbol '>'.
Loop operations 4-6 in your python script by using while or for statement until get all host name and contents of www of all 100 servers.
I need to connect to a server with SSH to download files. I have Ubuntu and I've set up SSH in the standard way: I have a ssh_config file in .ssh which defines a host entry (say host_key) for the server address (Hostname.com) and username, and I've set up an RSA key. So when I try to log into SSH from the command line or bash, I just need to use ssh host_key
I would like to do this in Python. The standard solutions seems to be to use Paramiko to set up the connection. I tried this:
from paramiko import SSHClient
from scp import SCPClient
ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect('host_key')
scp = SCPClient(ssh.get_transport())
# etc...
However, it always seems to hang and time out on ssh.connect('host_key'). Even when I try to include the username and password: ssh.connect('host_key', username='usrnm', password='pswd').
Are my host keys not loading properly? And would this take care of the RSA keys as well?
It only works if I use the whole Hostname.com with username and typed-out password. Which is maybe a bit insecure.
Since paramiko has a SSHConfig class, you can use it for your ~/.ssh/config.
However, it is slightly messy, I recommend you to use fabric instead of that.
Here is the code example:
from fabric.api import put
put('local path', 'remote path')
I do not think that it is common to use ssh_config file with Paramiko (or any other code/language). ssh_config is a configuration file for OpenSSH tools, not for SSH in general.
Usually, you specify your private key directly in your code as an argument of SSHClient.connect method:
How to access to a remote server using Paramiko with a public key-file
If you want to keep using ssh_config, Paramiko can parse it. Check parse_ssh_config and lookup_ssh_host_config functions. But I believe, you still have to look up the key file from the config and pass it explicitly to SSHClient.connect method.
Say if I wanted to run vim ./foo.txt I want to be able to edit foo.txt with my tcp socket client.
But whenever I try to do this it executes on the server but not on my client.
I do not want to use paramiko or any other ssh-like modules I want to stay using the python socket module.
I am using python 3.
I would suggest opening a command on the server (where the file is) with the subprocess module. This way to can keep putting information into it. You can have the client send a message which tells the server to send x to the subprocess.
An example would be like this:
import subprocess
# Assuming the variable x is that the socket is sending the server...
editing_foo = subprocess.Popen(['vim', './foo.txt'], stdin=PIPE) # stdin must be PIPE to communicate
editing_foo.communicate(input=x) # input is a string which is sent to the subprocess
# x could have been 'i' or ':q!' for example
I am creating a python application using twisted which reads lines from a serial port.
In order to (unit)test that app without having to connect an actual device to the serial port (also on pc's without an actual serial port) I would like to create a python script/app that sets up a virtual serial port and writes to it, so the twisted app can connect to the other end of the virtual serial port and read from it. This way I can write some unittests.
I found this is possible using pseudo terminals in linux. I also found a working example script on https://askubuntu.com/questions/9396/virtual-serial-port-for-testing-purpose.
I would like to change that script to a class on which I can call a write method to write data to the serial port, and then test the twisted app.
This example script does a lot of stuff with poll and select and a linux stty command which I don't really understand. I hope someone can fill the gap in my knowledge or provide some hints.
Cheers,
Dolf.
In addition to what Jean-Paul Calderone said (which was the correct answer mostly), I also made the following script in python, using socat.
This can be imported and instantiated into an interpreter, and then you can use it's writeLine method to write data to a (vritual) serial port, which is connected through socat to another (virtual) serial port, on which another twisted app can be listening. But as Jean-Paul Calderone said: if it's just unittesting you want, you don't really need to do this stuff. Just read the docs he mentioned.
import os, subprocess, serial, time
from ConfigParser import SafeConfigParser
class SerialEmulator(object):
def __init__(self,configfile):
config=SafeConfigParser()
config.readfp(open(configfile,'r'))
self.inport=os.path.expanduser(config.get('virtualSerialPorts','inport'))
self.outport=os.path.expanduser(config.get('virtualSerialPorts','outport'))
cmd=['/usr/bin/socat','-d','-d','PTY,link=%s,raw,echo=1'%self.inport,'PTY,link=%s,raw,echo=1'%self.outport]
self.proc=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
time.sleep(3)
self.serial=serial.Serial(self.inport)
self.err=''
self.out=''
def writeLine(self,line):
line=line.strip('\r\n')
self.serial.write('%s\r\n'%line)
def __del__(self):
self.stop()
def stop(self):
self.proc.kill()
self.out,self.err=self.proc.communicate()
You don't need a pty to test your protocol. You don't even need any kind of file descriptor. Follow the guidelines at http://twistedmatrix.com/documents/current/core/howto/trial.html, particularly the Testing a protocol section.
A better approach is probably to use a software null modem emulator.
You can get it from github for linux and from sourceforge for windows.
On linux it is called tty0tty and you simply type
make
to build everything. Then you would need to type
sudo insmod module/tty0tty.ko
to install the virtual driver and
./pts/tty0tty
to launch the application, which opens you 2 virtual ports: /dev/pts/4 and /dev/pts/6.
You can then open the /dev/pts/4 serial port in your python unit tests and open the /dev/pts/6 in your application.
In your python unit test, you would just type something like:
import serial
ser = serial.Serial('/dev/pts/4', 19200)
How can I read data from a big remote file using subprocess and ssh?
import subprocess
ssh = subprocess.Popen(['ssh', 'user#host', 'cat', 'path/to/file'],
stdout=subprocess.PIPE)
for line in ssh.stdout:
line # do stuff
The answer above will work, but you'll have to setup your ssh login to use no password between your boxes. There are other ways to transfer files between computers using Python. A simple way, without authentication is to setup an apache server and use an http request.
For performance improvement, which is important when the file is big, there is rsync. For more information about the exact improvement see following post and the answer from Rafa:
How does `scp` differ from `rsync`?
The algorithm would then be the following using rsync
import subprocess
subprocess.Popen(["rsync", host-ip+'/path/to/file'],stdout=subprocess.PIPE)
for line in ssh.stdout:
line # do stuff
Use iter with readline to read each full line:
for i in iter(f.stdout.readline,"")