I used to get a fixed image file from a fixed server every month and make regular meeting materials, It was troublesome to dive and get it with WinSCP, so I decided to automate it with Python.
When I checked it, it seemed that I could do it using paramiko and scp, so I tried it.
Execution side: Windows Server 2012 Obtained from: CentOS Linux 7
For terminals connected to the Internet, normal pip is fine
py -m pip install paramiko
If you are in an offline environment, download it once and then install it.
py -m pip download -d C:\tmp --no-binary :all: paramiko
When I typed the above command
ERROR: Command errored out with exit status 1:
I got an error saying that I could not download.
After fighting for a while
py -m pip download -d C:\tmp paramiko
I was able to download it at.
The --no-binary
option downloads the source, not the binary
(It makes it less susceptible to the environment), but it doesn't seem to work well with it.
Take the downloaded file to the installation destination and install it with the following command.
pip install --no-index --find-links=tmp paramiko
I wasn't sure why I couldn't do it the usual way, but in my environment it works fine with the above.
First of all, let's try to make ʻimport paramiko`. If you cannot, there is a problem with the installation method.
First of all, I will put the necessary code.
import paramiko
import scp
#Server login information
host = "IP address"
user = "User name"
pas = "password"
#Output directory
out_path = r"C:\temp"
#Target file path
target_path = "/var/tmp/hoge.log"
#Server connection
with paramiko.SSHClient() as sshc:
sshc.set_missing_host_key_policy(paramiko.AutoAddPolicy())
sshc.connect(hostname=host, port=22, username=user, password=pas)
#Copy processing by SCP
with scp.SCPClient(sshc.get_transport()) as scpc:
scpc.get(remote_path=target_path, local_path=out_path)
I haven't tried various things yet, so I don't understand the details, but somehow.
scpc.get(remote_path=target_path, local_path=out_path)
Regarding the two arguments here, it seems that only the string type is accepted.
Convert some useful * Path * objects to strings with str ()
etc. before passing them.
By the way, even if you don't declare the element
scpc.get(target_path, out_path)
It works fine with. However, since this function has other arguments, it is specified as a magic.
I felt it was simple and very easy to use.
In Linux, the hierarchy delimiter is /
instead of \
, so it is easy to combine with a simple string.
(Of course, Windows \
can also be treated as a character string)
In my case, I created the target file list while looping as shown below.
for day in day_list:
target_list.append(f"{port}/result{port}-{day}.png ")
You can also execute commands with paramiko
, but that is summarized separately.
Recommended Posts