Use pysmb to operate the smb server as annoymous user - smb

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()

Related

Python: Port Scanner -- No port is shown

import socket
from IPy import IP
def scan(target, port_num):
converted_ip = check_ip(target)
print(f"\n [-_0 Scanning Target]: {target}")
for port in range(1, port_num):
scan_port(converted_ip, port)
def check_ip(ip):
try:
IP(ip)
return (ip)
except ValueError:
return socket.gethostbyname(ip)
def get_banner(s):
return s.recv(1024)
def scan_port(ipaddress, port):
try:
sock = socket.socket()
sock.settimeout(0.5)
sock.connect((ipaddress, port))
try:
banner = get_banner(sock)
print(f"[+] Open Port {port}: {banner.decode().strip()}")
except:
print(f"[+] open Port {port}")
except:
pass
if __name__ == "__main__":
targets = input("[+] Enter Targets to Scan (split multiple targets with ,): ")
port_num = input("Enter Numbers of Ports you want to Scan: ")
if ',' in targets:
for ip_add in targets.split(","):
scan(ip_add.strip(" "), port_num)
else:
scan(targets, port_num)
guys, I wrote a simple port scanner as above, but whenever I tried to scan the ip address(IPv$) of my computer, or linux system in my vitual machine, no open port is shown.
Q1. Can someone tell me how to fix this?
Thank you for your help.

boto3 aws ec2 status/instance check fail email script

Hi I am trying to run a schedule script, not via lambda but from a pc or onsite schedule job - maybe every 10 mins or so to check all my ec2 instances are failing any system/instance status checks. If it fails then send email of the ec2 instance that failing - just send the name. Do not reboot
so here is what i have
import boto3
import smtplib
region_name='us-west-1'
#ec2_client = boto3.client('ec2')
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
#response = ec2_client.describe_instance_status(IncludeAllInstances = True)
client = boto3.client("ec2")
clientsns = boto3.client("sns")
#response = clientsns.create_topic
status = client.describe_instance_status(IncludeAllInstances = True)
#for instance in response['InstanceStatuses']:
# instance_id = instance['InstanceId']
# system_status = instance['SystemStatus']
# instance_status = instance['InstanceStatus']
# print (instance_id, system_status, instance_status)
for i in status["InstanceStatuses"]:
print("AvailabilityZone :", i["AvailabilityZone"])
print("InstanceId :", i["InstanceId"])
print("InstanceState :", i["InstanceState"])
print("InstanceStatus", i["InstanceStatus"])
print("SystemStatus", i["SystemStatus"])
in_status = i['InstanceStatus']['Details'][0]['Status']
sys_status = i['SystemStatus']['Details'][0]['Status']
msg1 = 'The following instances failed status checks, i[{InstanceId}]'
msg2 = 'All Instances passed System/instance checks!'
# check statuses
if ((in_status != 'passed') or (sys_status != 'passed')):
print(bcolors.WARNING + 'Reboot required for', i["InstanceId"] + bcolors.ENDC)
clientsns.publish(TopicArn='arn:aws:sns:us-west-1:462518063038:test',Message=msg1)
else:
print('All Instances passed System/instance checks!')
clientsns.publish(TopicArn='arn:aws:sns:us-west-1:462518063038:test',Message=msg2)
The problem I have is its sending one message per instance. I just wwant to sent one email for all instances. any idea?
Thank you

Asychronous server hanging in python

Am currently using python asynchronous server to server some clients , the server works well at first then eventually hangs without showing if it is receiving and requests from clients, when I press ctr-c it then shows that it receives the requests from the clients and it does not stop, it just continues to revieve requests .
I don't where this bug is emanating from.
Thank u in advance
import asyncio, json
from collections import Coroutine
from typing import Any
import Engine
import struct
header_struct = struct.Struct("!Q") # messages up to 2**64 - 1 in length
async def recvall(reader, length):
blocks = []
while length:
block = await reader.read(length)
if not block:
raise EOFError('socket closed with {} bytes left in this block'.format(length))
length -= len(block)
blocks.append(block)
return b''.join(blocks)
async def get_block(reader):
data = await recvall(reader, header_struct.size)
(block_length,) = header_struct.unpack(data)
return await recvall(reader, block_length)
async def put_block(writer, message):
block_length = len(message)
writer.write(header_struct.pack(block_length))
writer.write(message)
# await writer.drain()
async def handle_conversation(reader, writer):
address__ = writer.get_extra_info("peername")
print("Accepted connection from {}".format(address__))
while True:
# ************************try to check if there data to send*********************************
try:
block = await get_block(reader)
# decode the data
data = block.decode()
decoded_data = json.loads(data)
# dont forget to make this synchronous
answer = await Engine.get_answer(decoded_data["Task"], decoded_data["content"])
# don't forget to check in there is necessary data to push and making sure data is conveyed
await put_block(writer, answer)
print(answer)
except Exception as e:
raise
if __name__ == '__main__':
address = Engine.parse_command_line("asyncio server using coroutine")
# loop = asyncio.get_event_loop()
# coro = asyncio.start_server(handle_conversation, *address)
async def main():
server = await asyncio.start_server(
handle_conversation, *address)
addr = server.sockets[0].getsockname()
print(f'Serving on {addr}')
async with server:
await server.serve_forever()
asyncio.run(main(), debug=True)
Engine Code
import argparse
import json
import time
import upload_pic_and_search
import accept_connections
import connect
import opinion_poll
import share
import zmq
from jsonrpclib import Server
context = zmq.Context()
aphorisms = {"share": share.share_,
"poll": opinion_poll.add_poll,
"add_profile_pic": upload_pic_and_search.profile_pic,
"connect": connect.connect,
"accept_connection": accept_connections.accept_connection}
def sighn_up(doc):
"""this function will connect to sighn up """
proxy = Server('http://localhost:7002')
answer = proxy.sighn_up(doc)
return answer
def Verification(doc):
"""Code verification routine"""
proxy = Server('http://localhost:7002')
answer = proxy.verify(doc)
return answer
def login(doc):
"""This function handkes authetication"""
proxy = Server('http://localhost:7002')
answer = proxy.autheticate(doc)
return answer
def post(doc):
"""connect to server that handles posts"""
proxy = Server('http://localhost:6700')
answer = proxy.post(doc)
return answer
def comment(doc):
"""connect to the server that stores comments"""
proxy = Server('http://localhost:6701')
answer = proxy.comments_(doc)
return answer
def reply(doc):
"""store the reply"""
proxy = Server('http://localhost:6702')
answer = proxy.reply(doc)
return answer
def share(doc):
"""share the post"""
proxy = Server('http://localhost:6703')
answer = proxy.share(doc)
return answer
def likes(doc):
"""connect to the likes queue"""
zcontext = zmq.Context()
osock = zcontext.socket(zmq.PUSH)
osock.connect("tcp://127.0.0.1:6704")
osock.send_json(doc)
return {"Task": "like", "like": True}
def follow(doc):
"""handles the follow coroutine"""
zcontext = zmq.Context()
osock = zcontext.socket(zmq.PUSH)
osock.connect("tcp://127.0.0.1:6705")
osock.send_json(doc)
def connect(doc):
"""connect to routine for connection"""
zcontext = zmq.Context()
osock = zcontext.socket(zmq.PUSH)
osock.connect("tcp://127.0.0.1:6706")
osock.send_json(doc)
def accept_connection(doc):
"""the queue responsible accepting connections"""
zcontext = zmq.Context()
osock = zcontext.socket(zmq.PUSH)
osock.connect("tcp://127.0.0.1:6707")
osock.send_json(doc)
def add_profile_pic(doc):
"""Add the profile pic of the user"""
proxy = Server('http://localhost:7006')
answer = proxy.profile_pic(doc)
return answer
def search(doc):
"""search the user in the database"""
proxy = Server('http://localhost:7006')
answer = proxy.search(doc)
return answer
def profile(doc):
"""search the user in the database"""
proxy = Server('http://localhost:7006')
answer = proxy.profile(doc)
return answer
async def get_answer(aphorism, content):
"""Return the response to particular question"""
# time.sleep(0.0)
# fetch responsible function
# function = aphorisms.get(aphorism, "Error:Unknown aphorism.")
function = eval(aphorism)
answer = function(content)
return send(answer)
def send(data):
"""Prepare the data to be sent via socket"""
json_data = json.dumps(data)
data_bytes = json_data.encode()
return data_bytes
def parse_command_line(description):
"""arse command line and return a socket address."""
parser = argparse.ArgumentParser(description=description)
parser.add_argument('host', help="IP or hostname")
parser.add_argument("-p", metavar='port', type=int, default=1060, help="TCP port (default 1060)")
args = parser.parse_args()
address = (args.host, args.p)
return address
def recv_untill(sock, suffix):
"""Receive bytes over socket `sock` until we receive the `suffix`."""
message = sock.recv(4096)
if not message:
raise EOFError("Socket closed")
while not message.endswith(suffix):
data = sock.recv(4096)
if not data:
raise IOError('received {!r} then socket closed'.format(message))
message += data
return message

I am trying to bundle my Python(3.5.3) Tkinter app using cx_Freeze(5.1.1). When I hide my command prompt the app doesn't work.

As suggested here I use it to hide my command prompt in my setup.py file. It does hide my command prompt but the app does not work. Basically I am trying to make a Windows native Microsoft MSI for my GUI that I have built for youtube-dl command line tool that is used to consume media from some of the most popular video hosting sites. Any help is much appreciated. Here is my app.py:-
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from tkinter import filedialog
from tkinter.ttk import Progressbar
import youtube_dl
import threading
import os
download_folder = os.path.expanduser("~")+"/Downloads/"
download_folder_chosen = ""
window = Tk()
window.title("IOB Youtube Downloader")
window.geometry('510x100')
def my_hook(d):
if d:
if d['status'] == 'downloading':
percent_done = d['_percent_str']
percent_done = percent_done.replace(" ", "")
percent_done = percent_done.replace("%", "")
bar['value'] = percent_done
bar.grid(column=1, row=2, pady=15)
bar_lbl.configure(text=percent_done + "%")
bar_lbl.grid(column=1, row=3)
txt['state'] = DISABLED
btn['state'] = DISABLED
if d['status'] == 'finished':
bar.grid_forget()
txt['state'] = NORMAL
btn['state'] = NORMAL
bar_lbl.configure(text="Download Completed !!!")
bar_lbl.grid(column=1, row=2)
messagebox.showinfo('IOB Youtube Downloader', 'Download Complete')
if d['status'] == 'error':
print("\n"*10)
print(d)
messagebox.showerror('IOB Youtube Downloader', 'Download Error')
else:
bar_lbl.configure(text="Download Error. Please try again !!!")
bar_lbl.grid(column=1, row=2)
def start_thread():
t1 = threading.Thread(target=clicked, args=())
t1.start()
def clicked():
res = txt.get()
if download_folder_chosen != "":
location = download_folder_chosen + "/"
else:
location = download_folder
ydl_opts = {
'progress_hooks': [my_hook],
'format': 'best',
'outtmpl': location + u'%(title)s-%(id)s.%(ext)s',
}
try:
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([res])
except:
messagebox.showerror('IOB Youtube Downloader', 'Download Error')
def choose_directory():
global download_folder_chosen
current_directory = filedialog.askdirectory()
download_folder_chosen = current_directory
messagebox.showinfo('IOB Youtube Downloader', 'Download Location:- ' + download_folder_chosen)
style = ttk.Style()
style.theme_use('default')
style.configure("blue.Horizontal.TProgressbar", background='blue')
bar = Progressbar(window, length=200, style='black.Horizontal.TProgressbar')
bar_lbl = Label(window, text="")
lbl = Label(window, text="Paste URL")
lbl.grid(column=0, row=0)
txt = Entry(window,width=60)
txt.grid(column=1, row=0)
btn = Button(window, text="Download", command=start_thread)
btn.grid(column=2, row=0)
btn2 = Button(window, text="...", command=choose_directory)
btn2.grid(column=3, row=0)
window.iconbitmap('favicon.ico')
window.mainloop()
And here is my setup.py file that I use to build the bundle exe using cx_Freeze.
from cx_Freeze import setup, Executable
import sys
import os
base = None
if sys.platform == 'win32':
base = "Win32GUI"
os.environ["TCL_LIBRARY"] = r"C:\Python35\tcl\tcl8.6"
os.environ["TK_LIBRARY"] = r"C:\Python35\tcl\tk8.6"
setup(
name = "IOB Youtube Downloader",
options = {"build_exe": {"packages":["tkinter",], "include_files":[r"C:\Python35\DLLs\tk86t.dll", r"C:\Python35\DLLs\tcl86t.dll", r"E:\Youtube_Downloader\Src\favicon.ico"]}},
version = "1.0",
author = "IO-Bridges",
description = "Download videos from all popular video streaming sites.",
executables = [Executable
(
r"downloader.py",
# base=base, <---- Here setting the base
shortcutName="IOB Youtube Downloader",
shortcutDir="DesktopFolder",
icon="favicon.ico"
)]
)

ftp sychronizer by pyftpsync not working

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)

Resources