I am trying to send a file from my PC to many servers to a specific folder in the server directory using one script, for keeping things simple, I am trying in the beginning to send one file to one server instead of many.
I am already connected to a server using a key for authentication, so I do not need to use any login info in my code. I have used the following:
import pysftp as sftp
def Filetransfer():
try:
s = sftp.Connection(host='IP address')# this is where the server ip address is inserted
remotepath='/xx/yy/file.txt'# where my file will be transferred to
localpath='C:/Users/David/Desktop/file.txt'# this is the file location in my PC
s.put(localpath,remotepath)
s.close()
except Exception, e:
print str(e)
Filetransfer()
I get the following Exception:
AttributeError: "'Connection' object has no attribute '_transport_live'" in <bound method Connection.__del__ of <pysftp.Connection object at 0x0000000002E1F3C8>>
I have tried to insert the server port beside the IP address, it did not help as I get the same error.
Use this
sftp.Connection(host="your_host", port="your_port", username="user_name", private_key="private_key")
if you're still having problems change private_key to password
check out the documentation
http://pysftp.readthedocs.org/en/release_0.2.8/pysftp.html
Related
I use mcpi: https://github.com/AdventuresInMinecraft/AdventuresInMinecraft-Linux
Starting the local server.
After, run program:
import mcpi.minecraft as minecraft
mc = minecraft.Minecraft.create()
mc.postToChat("Hello Minecraft World")
I am facing the below error:
Traceback (most recent call last):
File "/home/home/AdventuresInMinecraft/MyAdventures/HelloMinecraftWorld.py", line 2, in mc = minecraft.Minecraft.create()
File "/home/home/.local/lib/python3.6/site-packages/mcpi/minecraft.py", line 376, in create return Minecraft(Connection(address, port))
File "/home/home/.local/lib/python3.6/site-packages/mcpi/connection.py", line 17, in init self.socket.connect((address, port))
ConnectionRefusedError: [Errno 111] Connection refused
A ConnectionRefusedError means that the address + port combination was unable to be secured for this particular Minecraft server and thus raised an exception. This could be because some other application is already using the port of interest, the port is unavailable because of the OS, or a handful of other networking configuration mishaps.
But perhaps a better series of questions to ask yourself is:
What is the default address and port that minecraft.Minecraft.create() will attempt to launch / listen at?
Do I have access to that server (address + port)?
If I do have access, are there any security issues (AKA Firewall)?
This post has already addressed the root issue of your question, and I hope it gives you a good start at understanding the foundation of your problem.
Notice how their question mentions s.connect((host,port)) and your stack trace has self.socket.connect((address, port)) Looks like the same thing to me!
Some more reading:
- localhost
- check if port is in use
I encountered the same issue. I looked into the code of mcpi and found that the default port is 4711. However, a Minecraft Server's default port is 25565. All you need to do is add 2 parameters on the create() function. Code(Python):
mc = minecraft.Minecraft.create(address="127.0.0.1", port=25565)
btw change "address" in the code to the host of the server (only if you modified the "server.properties" file).
Also, ConnectionRefusedError doesn't mean that it's not secured, I believe it means that either the server is not online, it doesn't exist, or the server refused it for some reason.
EDIT:
Oops sorry I just found out that mcpi actually connects to the RaspberryJam plugin which is hosted on another IP and port. The plugin runs on port 4711. So mcpi has the right port.
So check if you have the RaspberryJam plugin installed. If not, download it from
https://www.spigotmc.org/resources/raspberryjuice.22724/
And put the .jar file inside the plugins folder in your server directory.
I use Paramiko to put a file to an SFTP server:
import paramiko
transport = paramiko.Transport((host, port))
transport.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put(local_path, remote_path)
Now, I would like to check if it worked. The idea is that I compare the checksum of the local file and the remote one (that is located on the SFTP server).
Does Paramiko functionality allows to do that? If it is the case, how exactly it works?
With the SFTP, running over an encrypted SSH session, there's no chance the file contents could get corrupted while transferring. So unless it gets corrupted when reading the local file or writing the remote file, you can be pretty sure that the file was uploaded correctly, if the .put does not throw any error.
try:
sftp.put(local_path, remote_path)
except:
# Something went wrong
If you want to test explicitly anyway:
While there's the check-file extension to the SFTP protocol to calculate a remote file checksum, it's not widely supported. Particularly it's not supported by the most widespread SFTP server implementation, the OpenSSH. See What SFTP server implementations support check-file extension.
If you are lucky to connect to another SFTP server that supports the extension, you can use the Paramiko's SFTPFile.check method.
If not, your only option is to download the file back and compare locally.
If you have a shell access to the server, you can of course try to run some shell checksum command (sha256sum) over a separate shell/SSH connection (or channel) and parse the results. But that's not an SFTP solution anymore. See Comparing MD5 of downloaded files against files on an SFTP server in Python.
if the file doesn't upload then the method will throw an error, so u can check for error
import paramiko
transport = paramiko.Transport((host, port))
transport.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(transport)
try:
sftp.put(local_path, remote_path)
except IOError:
#'Failure'
except OSError:
#'Failure'
I am writing TLS server in Python. I accept a connection from a client, wrap the socket and then try to read data - without success.
My server inherits from socketserver.TCPServer. My socket is non-blocking - I overwrote server_bind() method. Socket is wrapped, but handshake has to be done separately, because of the exception which is raised otherwise:
def get_request(self):
cli_sock, cli_addr = self.socket.accept()
ssl_sock = ssl.wrap_socket(cli_sock,
server_side=True,
certfile='/path/to/server.crt',
keyfile='/path/to/server.key',
ssl_version=ssl.PROTOCOL_TLSv1,
do_handshake_on_connect=False)
try:
ssl_sock.do_handshake()
except ssl.SSLError as e:
if e.args[1].find("SSLV3_ALERT_CERTIFICATE_UNKNOWN") == -1:
raise
return ssl_sock, cli_addr
To handle received data, I created a class which inherits from socketserver.StreamRequestHandler (I tried also with BaseRequestHandler, but with no luck, ended with the same problem - no data received).
When I print self.connection in handle() method, I can see that it is of type SSLSocket, fd is set (to some positive value), both local and remote IP and port have values as expected, so I assume that a client is successfully connected to my server and the connection is opened. However when I try to read data
self.connection.read(1)
There should be more bytes received, I tried with 1, 10, 1024, but it does not make any difference, the read() method always returns nothing. I tried to check len or print it, but there is nothing to be printed.
I was monitoring packages using Wireshark. And I can see that the data I am expecting to read, comes to my server (I checked that IP and port are the same for self.connection and in Wireshark), which sends ACK and then receives FIN+ACK from the client. So it looks like the data comes and are handled properly on a low level, but somehow read() method is not able to access it.
If I remove wrap_socket() call, then I am able to read data, but that is some data which client is sending for authentication.
I am using Python 3.4 on Mac machine.
How is that possible that I can in Wireshark that packets are coming, but I am not able to read the data in my code?
I'm on Windows 7.
I cannot connect to my iPad with a simple Python script:
HOST = '192.168.1.122'
try:
f = ftplib.FTP(HOST)
except (socket.error, socket.gaierror), e:
MessageBox.Show('ERROR: cannot reach "%s"' % HOST)
return
try:
f.connect(HOST,2121)
f.login()
except ftplib.error_perm:
MessageBox.Show('ERROR: cannot login anonymously')
f.quit()
return
The errors I have is "getaddrinfo returns an empty list" and the "cannot reach..." message... Cannot solve it...
I tried to FTP with several programs on the iPad without success. If I FTP via DOS box or using a FTP software it works. I tried as well another FTP server on my PC and it works.
I am forced to use port 2121, so can't change it.
Any clue or experience?
You should read docs before anything:
class ftplib.FTP([host[, user[,
passwd[, acct[, timeout]]]]]) Return a
new instance of the FTP class. When
host is given, the method call
connect(host) is made. When user is
given, additionally the method call
login(user, passwd, acct) is made
(where passwd and acct default to the
empty string when not given). The
optional timeout parameter specifies a
timeout in seconds for blocking
operations like the connection attempt
(if is not specified, the global
default timeout setting will be used).
So, if you do f = ftplib.FTP(HOST) it fails because it will try to connect to standard port (21) and not 2121.
You should get an instance of ftplib and later use f.connect(HOST, 2121).
http://docs.python.org/library/ftplib.html
I'm trying to use paramiko to get a file via SFTP.
It connects, I can list directories and it even downloads the first megabyte or so of the file but then it just hangs. No exception, no error, nothing. It just hangs there indefinitely.
Here's the code I'm working with:
import paramiko
t = paramiko.Transport( host )
t.connect( username=uname, password=passwd )
f = paramiko.SFTPClient.from_transport( t )
print f.listdir()
f.get( fname, fname ) #it hangs on this line :\
I have sftp access to the host in question but no shell access.
The host contains a single file that I need to fetch regularly and process in a python script.
Any help with this problem or alternate solutions to doing SFTP in Python are greatly appreciated :)
I was experiencing the same problem as Ulfur. He posted his own fix/workaround as a comment to another answer, so I decided to add it as a proper answer to make it more visible.
The basic idea is to not use the .get() method, but to loop over the lines. The following is a Python 3 implementation.
transport = None
sftp = None
sftp_path = 'some/sftp/path'
dst_path = '/some/local/path'
try:
transport = paramiko.Transport((SFTP_HOST, SFTP_PORT))
transport.set_log_channel('delapi')
transport.connect(username=SFTP_USER, password=SFTP_PASS)
sftp = paramiko.SFTPClient.from_transport(transport)
with sftp.open(sftp_path, 'r') as remote:
with open(dst_path, 'w') as local:
for line in remote:
local.write(line)
except SSHException:
print("SSH error")
finally:
if sftp:
sftp.close()
if transport:
transport.close()
I suggest you fire up Wireshark on the client and see what's happening at the protocol level. You won't be able to read the data in the packets as it will be encrypted, but you will see what's going on at the TCP/IP level and that might provide a clue.