ftp sychronizer by pyftpsync not working - ftp

I need to synchronize my server (openshift RHC Server) with one ftp server.
SO i used this code:
from ftpsync.synchronizers import DownloadSynchronizer, UploadSynchronizer,BiDirSynchronizer
from ftpsync.targets import FsTarget#,UploadSynchronizer
from ftpsync.ftp_target import FtpTarget
import os
local_folder = os.environ['HOME']
local = FsTarget("/tmp")
user ="u707539103"
passwd = "ss12346"
remote = FtpTarget("/home/u707539103/public_html", "93.188.160.113", 21,user, passwd)
opts = {"force": False, "delete_unmatched": True, "verbose": 3, "dry_run" : False}
s = UploadSynchronizer(local, remote, opts)
s.run()
but i get error:
File "/var/lib/openshift/55c50b0d89f5cfa8bd0000e8/app-root/runtime/srv/python/lib/python2.7/site-packages/pyftpsync-1.0.3-py2.7.egg/ftpsync/ftp_target.py", line 99, in open
self.ftp.cwd(self.root_dir)
File "/var/lib/openshift/55c50b0d89f5cfa8bd0000e8/app-root/runtime/srv/python/lib/python2.7/ftplib.py", line 553, in cwd
return self.voidcmd(cmd)
File "/var/lib/openshift/55c50b0d89f5cfa8bd0000e8/app-root/runtime/srv/python/lib/python2.7/ftplib.py", line 249, in voidcmd
return self.voidresp()
File "/var/lib/openshift/55c50b0d89f5cfa8bd0000e8/app-root/runtime/srv/python/lib/python2.7/ftplib.py", line 224, in voidresp
resp = self.getresp()
File "/var/lib/openshift/55c50b0d89f5cfa8bd0000e8/app-root/runtime/srv/python/lib/python2.7/ftplib.py", line 219, in getresp
raise error_perm, resp
ftplib.error_perm: 530 You aren't logged in
So what is the problem?

Not sure what your environment is, but a typical root cause of "Servname not supported for ai_socktype" is missing or lacks in /etc/services. The following lines should be there:
ftp-data 20/udp # File Transfer [Default Data]
ftp-data 20/tcp # File Transfer [Default Data]
ftp 21/udp # File Transfer [Control]
ftp 21/tcp # File Transfer [Control]
and it's not necessary to include the port number when using the default...

finally i found answer and its code is here:
from ftpsync.synchronizers import DownloadSynchronizer, UploadSynchronizer,BiDirSynchronizer
from ftpsync.targets import FsTarget #, UploadSynchronizer, DownloadSynchronizer
from ftpsync.ftp_target import FtpTarget
import os
env_var = os.environ['OPENSHIFT_HOMEDIR']
#local = FsTarget(env_var+"/app-root/runtime/tmp/")
local = FsTarget('/tmp')
user ="u220290147"
passwd = "ss123456"
#ip='31.170.167.182';user='u364816941';# ss-22.4rog.in
#ip='31.170.167.90';user='u929884673';# iran-balabar.tk master#tb-simple.heliohost.org
ip='s.id.ai';user='u707539103';# s.id.ai soheil_paper#yahoo.om
#ip='tb-blog.4rog.in';user='u721167122';# tb-blog.4rog.in
#remote = FtpTarget("/home/"+user+"/public_html", "93.188.160.83", user, passwd)
remote = FtpTarget("/public_html", ip,21, user, passwd)
opts = {"force": False, "delete_unmatched": False, "verbose": 3, "execute": True, "dry_run" : False}
#opts = {"force": True, "delete_unmatched": True, "verbose": 3, "execute": True, "dry_run" : False}
s = UploadSynchronizer(local, remote, opts)
#s = DownloadSynchronizer(local, remote, opts)
s.run()
stats = s.get_stats()
print(stats)

Related

Serial Async Acquisition

I'ven't understood well the asyncio functionaly and I need a clarification.
I've checked that this code works:
from asyncio import get_event_loop
from serial_asyncio import open_serial_connection
async def main():
reader, writer = await open_serial_connection(url='COM10', baudrate=115200)
while True:
line = await reader.readline()
print(str(line, 'utf-8'))
asyncio.run(main())
basically the connection is established and I see messages coming from the serial port but it is not what I was expecting.
I'd like to start the acquisition from the serial and at the same time I'd like to go ahead doing other stuffs in my code.
Basically something like this one in scapy:
t = AsyncSniffer()
t.start()
print("Acquisition started")
wait (10)
t.stop()
I've also tried using the Thread option like this:
import serial
import threading
global stop_threads
import time
stop_threads=False
def thread_function_1():
ser = serial.Serial('COM1',115200)
while thread_function_1():
line=ser.readline()
if line:
string=line.decode()
print(string)
if stop_threads==true:
ser.close()
break
print ('print_1')
x= threading.Thread(name = "thread_function_1", target = thread_function_1)
x.start()
time.sleep(100)
stop_threads = True
print ('print_2')
x.join()
I'm getting this error which I cannot solve:
Traceback (most recent call last):
File "C:\Users\SIM\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\SIM\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\python\connessione_seriale.py", line 31, in thread_function_1
while thread_function_1():
File "C:\python\connessione_seriale.py", line 14, in thread_function_1
ser = serial.Serial('COM1',115200)
File "C:\Users\SIM\AppData\Local\Programs\Python\Python38\lib\site-packages\serial\serialwin32.py", line 33, in __init__
super(Serial, self).__init__(*args, **kwargs)
File "C:\Users\SIM\AppData\Local\Programs\Python\Python38\lib\site-packages\serial\serialutil.py", line 244, in __init__
self.open()
File "C:\Users\SIM\AppData\Local\Programs\Python\Python38\lib\site-packages\serial\serialwin32.py", line 64, in open
raise SerialException("could not open port {!r}: {!r}".format(self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM1': PermissionError(13, 'Access is denied.', None, 5)
the COM1 is available.I've tried to open it via putty and it works.
this is the solution I've found. I've used a thread inside a class in order to start/stop the serial acquisition when I need it.
class ThreadTest:
def seriale(self, n):
ser = serial.Serial('COM9', 115200, timeout=1)
time.sleep(2)
with open('C:/python/test.txt', 'w') as output:
if self._running==False:
ser.close()
while self._running and n > 0:
line = ser.readline()
#print (line)
n -= 1
if line:
# Converting Byte Strings into unicode strings
string = line.decode()
#print (string)
output.write(string)
def terminate(self):
self._running = False
def __init__(self):
self._running = True
c = ThreadTest()
t1 = Thread(target=c.seriale, args=(10,)) #10 are the seconds of the acquisition via serial and can be replaced
t1.start() # start of the serial acquisition
time.sleep(10)# here the sleep can be replaced with code
c.terminate()

Python script stuck in connecting to Windows computer and exits with error 107

I run this script:
The script runs in a loop on an host_ips, connects to each of them and runs a bat file in the command
from socket import *
from pypsexec.client import Client
class Windows(object):
def __init__(self, ip, username, password):
self.ip = ip
self.username = username
self.password = password
self.cmd_exe = "C:\\Windows\\System32\\cmd.exe"
self.windows_client = self.connect_to_windows_client()
def connect_to_windows_client(self):
windows_client = self.windows_connect(self.ip, self.username, self.password)
if windows_client is not None:
return windows_client
self.log.error("Connection error to {}".format(self.ip))
#staticmethod
def windows_connect(address, username, pwd):
try:
windows_client = Client(address, username=username, password=pwd, encrypt=False)
windows_client.connect()
windows_client.create_service()
return windows_client
except Exception:
print("Your Username and Password of " + getfqdn(address) + " are wrong.")
return False
xtenders = ['host_ip1', 'host_ip2']
def main():
for x in xtenders:
print x
x = Windows(x, "user_name", "password")
result = x.windows_client.run_executable('C:\\file_bat_directory\\file.bat')
x.windows_client.remove_service()
x.windows_client.disconnect()
print result
if __name__ == '__main__':
main()
Sometimes the script run ok, but sometimes it is stuck when he connect to machine, it is print the host_ip, waits a few minutes and exit with the following error:
'host_ip1'
Exception in thread msg_worker-'host_ip1':445:
Traceback (most recent call last):
File "/usr/lib64/python2.7/threading.py", line 812, in __bootstrap_inner
self.run()
File "/usr/lib64/python2.7/threading.py", line 765, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/amirh/.local/lib/python2.7/site-packages/smbprotocol/connection.py", line 1199, in _process_message_thread
self.disconnect(False)
File "/home/amirh/.local/lib/python2.7/site-packages/smbprotocol/connection.py", line 799, in disconnect
self.transport.close()
File "/home/amirh/.local/lib/python2.7/site-packages/smbprotocol/transport.py", line 89, in close
self._sock.shutdown(socket.SHUT_RDWR)
File "/usr/lib64/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
error: [Errno 107] Transport endpoint is not connected
Traceback (most recent call last):
File "file_name.py", line 44, in <module>
main()
File "file_name.py", line 39, in main
result = x.windows_client.run_executable('C:\\file_bat_directory\\file.bat')
File "/home/amirh/.local/lib/python2.7/site-packages/pypsexec/client.py", line 395, in run_executable
main_pipe.write(start_msg.pack(), 0)
File "/home/amirh/.local/lib/python2.7/site-packages/smbprotocol/open.py", line 1382, in write
return self._write_response(request, wait)
File "/home/amirh/.local/lib/python2.7/site-packages/smbprotocol/open.py", line 1388, in _write_response
response = self.connection.receive(request, wait=wait)
File "/home/amirh/.local/lib/python2.7/site-packages/smbprotocol/connection.py", line 859, in receive
self._check_worker_running() # The worker may have failed while waiting for the response, check again
File "/home/amirh/.local/lib/python2.7/site-packages/smbprotocol/connection.py", line 1004, in _check_worker_running
self.disconnect(False)
File "/home/amirh/.local/lib/python2.7/site-packages/smbprotocol/connection.py", line 799, in disconnect
self.transport.close()
File "/home/amirh/.local/lib/python2.7/site-packages/smbprotocol/transport.py", line 89, in close
self._sock.shutdown(socket.SHUT_RDWR)
File "/usr/lib64/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 107] Transport endpoint is not connected
How can I fix this?

Use pysmb to operate the smb server as annoymous user

This is the package I grabbed for someone else's smb server, it can log in to the server anonymously, but I can't。
enter image description here
I found that the difference between the packet I sent to the target and the one he sent is that there is Unicode password.
enter image description here
I've no idea how to remove the item.Below is my python code。
from smb import smb_structs
from smb.SMBConnection import SMBConnection
smb_structs.SUPPORT_EXTENDED_SECURITY = False
smb_structs.SMB_FLAGS_CANONICALIZED_PATHS = False
smb_structs.SMB_FLAGS2_UNICODE = False
smb_structs.SMB_FLAGS2_IS_LONG_NAME = False
smb_structs.SMB_FLAGS2_NT_STATUS = False
smb_structs.CAP_UNICODE = False
smb_structs.CAP_LARGE_FILES = False
smb_structs.CAP_STATUS32 = False
def transfer():
smb = SMBConnection(username, password, "", "IIE-BCHIOVTGH68<20>", sign_options=0, use_ntlm_v2=False)
try:
res = smb.connect(ip)
folders = smb.listShares()
for i in folders:
print(i.name)
except Exception as e:
print(e)
smb.close()
smb.close()
if __name__ == '__main__':
ip, port, username, password = '192.168.20.102', 139, "", ""
transfer()

How to interact with a running python script

As a start ive got a basic script which reads local unix syslog (/var/log/messages)
i want to build a tool which opens a socket (19999) locally and allows admin commands to be sent / processed.
As something i can build on basically i want to have the script on start up do the follow :
- open port 19999 locally
- start reading syslog storing "line" as the last line it has processed.
- when admin command of "printline" is seen print last known variable for "line"
Ive got basics done i think (script is below) where i have it open the relevant ports and it prints the commands sent to it from another client tool however it never starts to read the syslog.
#!/usr/bin/python
import socket
import subprocess
import sys
import time
from threading import Thread
MAX_LENGTH = 4096
def handle(clientsocket):
while 1:
buf = clientsocket.recv(MAX_LENGTH)
if buf == '': return #client terminated connection
print buf
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
PORT = 19999
HOST = '127.0.0.1'
serversocket.bind((HOST, PORT))
serversocket.listen(10)
while 1:
#accept connections from outside
(clientsocket, address) = serversocket.accept()
ct = Thread(target=handle, args=(clientsocket,))
ct.start()
def follow(thefile):
thefile.seek(0,2)
while True:
line = thefile.readline()
if not line:
time.sleep(0.1)
continue
yield line
if __name__ == '__main__':
logfile = open("/capture/log/uifitz/messages","r")
loglines = follow(logfile)
for line in loglines:
print line,
Any help would be appreciated. Python 2.6 by the way.

WinError 10038 an operaton was attempted on something that is not a socket

I'm trying to make chatting server in Python and I can't solve it. I'm running my code in CMD by using command python client.py localhost 9009.
this is the code that I am using:
#chat_client.py
import sys
import socket
import select
def chat_client():
if(len(sys.argv) < 3):
print("Usage: python chat_client.py hostname port")
sys.exit()
host = sys.argv[1]
port = int(sys.argv[2])
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(2)
# connect to remote host
try:
s.connect((host, port))
except:
print("Unable to connect")
sys.exit()
print("Connected to remote host. You can start sending messages")
sys.stdout.write("[Me] "); sys.stdout.flush()
while 1:
socket_list = [sys.stdin, s]
# Get the list sockets which are readable
read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
for sock in read_sockets:
if sock == s:
# incoming message from remote server, s
data = sock.recv(4096)
if not data:
print("\nDisconnected from chat server")
sys.exit()
else:
#print data
sys.stdout.write(data)
sys.stdout.write("[Me] "); sys.stdout.flush()
else:
# user entered a message
msg = sys.stdin.readline()
s.send(msg)
sys.stdout.write("[Me] "); sys.stdout.flush()
if __name__ == "__main__":
sys.exit(chat_client())
And this is the error that I'm getting:
I don't have a clue how to fix it. Help would be appreciated! :)
[Me] Traceback (most recent call last):
File "client.py", line 54, in <module>
sys.exit(chat_client())
File "client.py", line 32, in chat_client
read_sockets, write_sockets, error_sockets = select.select(socket_list , [],
[])

Resources