顯示具有 python 標籤的文章。 顯示所有文章
顯示具有 python 標籤的文章。 顯示所有文章

2024/07/01

之前使用的 honeyports 因為OS升到 almalinux 9不能使用了
almalinux 9 不再支援 python2
另外再找了一個差不多功能 有提供 python跟shell 可以使用
不過一樣有python2的問題
所以改用shell

程式要改一下

honeyport.sh 裡第20行是設定要listen在port 31337
如果有listen在其他 port 必須修改此行 存成不同檔案 再執行

為了能批次執行 改成如下

#PORT=31337;
PORT=$1;


再來寫個shell 如下 把要listen的 port 加上去

#!/bin/bash

#revice port want to listen
port="21 22 23 ......."

for i in $port
do
        /root/honeyport.sh $i &
done

執行後就可以在log 找到相關ip並進行處理了 


https://github.com/securitygeneration/Honeyport

2022/09/10

今天想使用 line 發群組通知

首先申請權杖

 

官方文件範例是使用 curl


$ curl -X POST -H 'Authorization: Bearer <access_token>' -F 'message=foobar' \

https://notify-api.line.me/api/notify

 

但試了半天發現一個問題 就是 message 無法換行 

找了好久才找到 範例如下


第一個方法


curl -X POST      -H 'Authorization: Bearer (your token)'      --data-binary message="%0A中文%0A123%0Aabc%0A456"      https://notify-api.line.me/api/notify


第二個方法

curl -X POST    -H 'Authorization: Bearer (your token)'   -d $'message=123\nabc'  https://notify-api.line.me/api/notify


使用python範例如下

檔名存為 line_notify.py

檔案內容如下


import requests

import sys


f = open(sys.argv[1])

msg = f.read()

f.close


def lineNotify(token, msg):

    url = "https://notify-api.line.me/api/notify"

    headers = {

        "Authorization": "Bearer " + token

    }

    payload = {'message': msg}

    r = requests.post(url, headers=headers, data=payload)

    return r.status_code


token = "your token"

lineNotify(token, msg)


只要指定檔案發送
檔案內是什麼內容
發送就是什麼內容

用法

python line_notify.py /tmp/txt_to_send


https://xenby.com/b/274-%E6%95%99%E5%AD%B8-%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8-line-notify-%E5%B0%8D%E7%BE%A4%E7%B5%84%E9%80%B2%E8%A1%8C%E9%80%9A%E7%9F%A5


https://officeguide.cc/python-line-notify-send-messages-images-tutorial-examples/


https://fm-aid.com/bbs2/viewtopic.php?pid=52815


https://notify-bot.line.me/zh_TW/


https://notify-bot.line.me/doc/en/

2022/05/26

因為要用linux shell 產生值再透過snmp server 讓 librenms 撈出後能畫圖

找到 python snmp server

只要一行指令

Standalone usage: snmp-server.py [-h] [-p PORT] [-c CONFIG] [-d] [-v]

SNMP server

optional arguments:
  -h, --help            show this help message and exit
  -p PORT, --port PORT  port (by default 161 - requires root privileges)
  -c CONFIG, --config CONFIG
                        OIDs config file
  -d, --debug           run in debug mode
  -v, --version         show program's version number and exit

要產生snmp值的範例檔如下

DATA = {
  '1.3.6.1.4.1.1.1.0': integer(12345),
  '1.3.6.1.4.1.1.2.0': bit_string('\x12\x34\x56\x78'),
  '1.3.6.1.4.1.1.3.0': octet_string('test'),
  '1.3.6.1.4.1.1.4.0': null(),
  '1.3.6.1.4.1.1.5.0': object_identifier('1.3.6.7.8.9'),
  # notice the wildcards:
  '1.3.6.1.4.1.1.6.*': lambda oid: octet_string('* {}'.format(oid)),
  '1.3.6.1.4.1.1.?.0': lambda oid: octet_string('? {}'.format(oid)),
  '1.3.6.1.4.1.2.1.0': real(1.2345),
  '1.3.6.1.4.1.3.1.0': double(12345.2345),


snmpwalk 指定 ip port

snmpwalk -c public -v 2c 10.1.1.1:1611 .1.2.3


 

2020/04/16

簡單記一下ipython 跟 notebook的安裝設定過程 讓遠端可以存取

先安裝

sudo apt install -y ipython ipython-notebook ipython-notebook-common

產生 config file
ipython profile create nbserver

使用ipython產生密碼 hash

In [1]: from notebook.auth import passwd
In [2]: passwd()

Enter password:
Verify password:
Out[2]: 'sha1:67c9e60bb8b6:9ffede0825894254b2e042ea597d771089e11aed'

修改

/home/user/.ipython/profile_nbserver/ipython_notebook_config.py

在檔案最後加上

c = get_config()
c.NotebookApp.ip = ‘*’
c.NotebookApp.open_browser = False
c.NotebookApp.port = 5678
c.NotebookApp.password = u'sha1:67c9e60bb8b6:9ffede0825894254b2e042ea597d771089e11aed'


啟動server
ipython notebook

接下來就可以在遠方使用browser

http://server_ip:5678

登入使用了

2019/10/20

今天在使用gnuplot
發現一個問題
當先進入gnuplot後再下指令畫圖
可以跳出另一個視窗
可是如果使用
gnuplot -e 的方式
畫面一閃就不見了
只能夠output到檔案

gnuplot -e "set terminal png; set output '/tmp/1.png'; plot '/tmp/33' with line"

另外如果在python 呼叫 gnuplot
也不能在視窗上顯示
只能夠output到檔案

語法如下

import Gnuplot

g = Gnuplot.Gnuplot()
g("set terminal png")
g("set output '/tmp/1.png'")
g.plot("'/tmp/33' with line")

記得要先 apt install  python-gnuplot

看圖指令
eog /tmp/1.png






















http://yurinfore.blogspot.com/2007/05/python.html

2019/10/16

https://otx.alienvault.com 是一個公開的情資交換平台
只要註冊帳號(免費) 就可以接收跟發布相關的情資
速度相當快
不要忘記訂閱自己感興趣的user
如 AlienVault
註冊完後有相關的訊息也會mail到註冊的信箱

而且也提供相關的API可以使用
因為目前寫python的几會比較多
所以簡單說明
首先要到https://github.com/AlienVault-OTX/OTX-Python-SDK下載
下載後直接執行
python setup.py install
就安裝完成了
再來我是直接到github找相關程式
以下這個是我覺得還不錯的
https://github.com/Neo23x0/signature-base/blob/master/threatintel/get-otx-iocs.py

下載後在執行前只要改以下二個地方
otx key只要註冊後就可以拿到

OTX_KEY = 'yout otx key'

以下改成拿回來的資料要放那裡
parser.add_argument('-o', metavar='dir', help='Output directory', default='/tmp')

改好後執行
/usr/bin/python Get-OTX-IOCs.py

就會在/tmp裡看到
otx-c2-iocs-ipv4.txt
otx-c2-iocs-ipv6.txt
otx-c2-iocs.txt
otx-filename-iocs.txt
otx-hash-iocs.txt
這些檔案
接下來就可以拿來應用了

也有人針對ip整理過 可以直接拿來用

不過最大的問題是 拿到這麼多的資料 一般firewall是不可能全部吃進去的
一定要找別的設備才能處理

2018/04/21

今天找到honeyports
程式碼是2013年的 用python寫
拿來當陷阱看來還不錯用

拿這個檔來修改
honeyports-0.4.py

預設執行時若偵測到try port的ip
會下iptables 並在畫面上出現訊息問管理者是要列出還是清掉加上的iptables
改一下程式
首先把出現訊息的地方mark掉
再來把加iptables的地方改成寫到log去
另外還有一個就是原作者在連線的回應訊息寫的是

nasty_msg = "\n\n***** Fuck You For Connecting *****\n\n"

這就看個人要不要改了

程式中的這些行因為是直接產生訊息在畫面上

Got connection from
Blocking the address: 
Creating a Linux Firewall Rule

I just blocked: 

如果不拿掉 在背景執行會有問題
不想拿也可以 就用screen來跑

改完後執行

sudo python honeyports-0.4.py -p 21
-p是監聽的port
可以多執行几次起在不同的port
大於1024可以不需要使用sudo
目前想到的是

21
22
23
137
138
139
445
1433
3389
3306
5800
5900

網卡多bind几個ip
然後.......就可以在log檔拿到這些ip了
接下來要作什麼
自己想


https://github.com/adhdproject/adhdproject.github.io/blob/master/Tools/HoneyPorts.md

https://github.com/ethack/honeyports

2018/02/17

之前要發mail都使用二種方法

1. 直接在需要寄信的主機上起一個mail server 來寄

2. 使用python

import smtplib,sys

sender = "test_from_hinet@hinet.net"
receipt = "abc@de.com
smtp = smtplib.SMTP("168.95.4.10")
header = "Subject: test outside in mail from hinet\r\n\r\n"
msg = "test outside in mail from hinet"
smtp.sendmail(sender, receipt, header+msg)
smtp.quit()

今天才知道 mutt 也可以設定到別台mail server寄信
設定方法是安裝好mutt後在user的家目錄設定 ~/.muttrc

加上以下這行
set smtp_url = "smtp://mail.server.ip:25/"
或在
/etc/Muttrc加上相同的內容
醬就可以了
mutt -s test abc@de.com -a test < test

2017/05/10

之前在centos上執行python的cgi都沒問題
但移植到ubuntu 16.04上後一直出現如下的error

File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 210, in execute
    query = query % args
TypeError: not all arguments converted during string formatting

程式完全一樣都沒改啊

google了半天 才解決問題
差異如下

ubuntu 16.04

sql = "delete from abc where ip=%s"
cursor.execute(sql, [ip])

變數一定要用 [ ] 包住

centos 7

sql = "delete from abc where ip=%s"
cursor.execute(sql, ip)


http://stackoverflow.com/questions/21740359/python-mysqldb-typeerror-not-all-arguments-converted-during-string-formatting

2016/11/21

因為有個單位是使用自行申請的ADSL
近來每天都打電話來說網路被鎖
在想說要不要寫個程式在user開机時把ip傳來同時在黑名單把ip刪掉
先找了一些資料

找出目前使用的ip

curl icanhazip.com

curl ipv4.icanhazip.com

wget -qO- icanhazip.com


在批次檔中使用ftp傳檔

ftp -s:upload.txt

upload.txt內容
open ftp.server.com
user@server.com
userpwd
prompt
cd ftp_upload
mput test.txt
bye


使用python拿到ip並寄出

import urllib2,smtplib,sys
response = urllib2.urlopen('http://icanhazip.com/')
html = response.read()
print html

sender = "test_from_hinet@hinet.net"
receipt = "abc@de.com"
smtp = smtplib.SMTP("168.95.4.10")
header = "Subject: ip \r\n\r\n"
msg = html
smtp.sendmail(sender, receipt, header+msg)
smtp.quit()


http://neochung.com/2015/01/pc/batch-file/windows%E4%B8%AD%E4%BD%BF%E7%94%A8%E6%89%B9%E6%AC%A1%E6%AA%94-bat-%E4%B8%8A%E5%82%B3ftp%E6%AA%94%E6%A1%88/

http://askubuntu.com/questions/95910/command-for-determining-my-public-ip

2016/06/27

最近的新增需求是要起一個ftp server
可是不想要用vsftp或其他daemon
所以直接使用pyftpdlib
還滿方便的 有很多範例可以直接套用
但用了後發現沒有log功能
再查了一下資料
發現只要加紅色二行就搞定了

import logging

from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
from pyftpdlib.authorizers import DummyAuthorizer

authorizer = DummyAuthorizer()
authorizer.add_user('user', '12345', '.', perm='elradfmwM')
handler = FTPHandler
handler.authorizer = authorizer

logging.basicConfig(filename='/var/log/pyftpd.log', level=logging.INFO)

server = FTPServer(('', 2121), handler)
server.serve_forever()

2016/06/18

在python中撈取mysql的資料
在cursor.execute後可以用cursor.fetchone()及cursor.fetchall()

如果回傳的只有一筆資料 可以使用cursor.fetchone() 可以少一點code
語法

cursor.execute(select count(*) from table)
result = cursor.fetchone()
print result[0]

如果回傳的資料有很多 則使用cursor.fetchall()

語法
cursor.execute(select * from table)
result = cursor.fetchall()
if result:
for record in result:
print record[0]


2016/06/17

今天又有一個需求
因為資料在計算的過程中會有時間差
所以有可能會產生二筆相同的資料
如下圖













可是因為某些原因
不希望讓使用者看到
原本想用DISTINCT來解決
但DISTINCT只能用在一個欄位
花時間找了一下資料
發現直接用group by就可以解決了

select user,ip from table group by ip;












http://tc.wangchao.net.cn/bbs/detail_1846934.html

2016/06/15

最近的工作就是一直用python來連mariadb

今天有個需求
要把從db撈出來的資料寫到檔案
找到這個方便的方法

cursor.execute("test from  test_table")
result = cursor.fetchall()
if result:
f = open("/tmp/data",'w')
        for record in result:
                print record[0],          #在畫面上印出資料
print>>f, record[0]    #把資料寫進檔案

2016/06/11

今天使用python要把資料塞進mysql時一直出問題
明明就有執行
也沒錯誤訊訊息
但資料就是沒進去
本來以為是跳脫字元的問題
試了也沒有
後來找到一個方便的語法
也不用再考慮單引號 雙引號要使用跳脫字元的情況
語法如下
最後的 db.commit() 一定要下
就是因為這個沒下
才試了一下午
最後還是問了高手才知道的

sql="insert into table values(%s,%s,%s,)"
cursor.execute(sql,(now,i,88888))
db.commit()

now是現在時間
i是變數
88888是數字

對應到table
datetime
varchar(50)
bigint(20)

2016/06/10

在shell 中呼叫 python 可以把變數一起丟給python

#!/bin/bash
var1=a
var2=b
python test.py $var1 $var2


test.py 內容如下

import sys
print sys.argv[0] # prints python_script.py
print sys.argv[1] # prints var1
print sys.argv[2] # prints var2


輸出結果為
test.py
a
b

2016/04/17

因為ascenflow GG了
所以把認証移到forti上去
順便想看一下線上人數並記錄
但找了一下forti的mib
並沒有提供這個值
所以只好自行寫程式來撈了

使用python來撈目前online user的所有資料 並從中取出線上人數 在輸出的最後一行
直接使用shell也可以

#!/usr/bin/python

import os
import telnetlib

host="192.168.1.1"
user="admin"
passwd="password"

tn = telnetlib.Telnet(host)

tn.read_until("FG600C login: ")
tn.write(user + "\n")
tn.read_until("Password: ")
tn.write(passwd + "\n")
tn.read_until("FG600C # ")
tn.write("diagnose firewall auth filter group auth_user_group(radius_server)" + "\n")
tn.read_until("FG600C # ")
tn.write("diagnose firewall auth list" + "\n")
#tn.read_until("FG600C # ")
tn.write("exit" + "\n")

print tn.read_all()
tn.close()

取出後把值吐給cacti來畫圖

步驟如下

1. 建立data input methods 使用自行寫好的程式










2. 使用步驟1 的資料來新增data templates














3.使用步驟2 的資料來產生 graph templates













4. 在forti上新增步驟3所產生的graph template






等待一段時間後畫出的圖如下












發現有小數出現 雖然說不太會影響判讀 但感覺就是怪怪的
找了一下資料
發現把graph template的gprint type改成exact numbers就可以顯示整數了













改好後如下圖 看起來正常多了









2016/04/06

如何使用python利用telnet指令到網路設備下指令並捉取回傳的資料
範例如下 

#!/usr/bin/python

import os
import telnetlib

host="1.1.1.1"
user="abc"
passwd="password"

tn = telnetlib.Telnet(host)
tn.read_until("login: ")
tn.write(user + "\n")
tn.read_until("Password: ")
tn.write(passwd + "\n")

#read_until()到下完password 即可 接下來的指令必須一直下
#不再使用read_until() 否則最後的 print tn.read_all() 會沒有資料

tn.write("ls -al" + "\n")
tn.write("exit" + "\n")
print tn.read_all()

2016/03/05

最近把從mysql撈資料的程式用python改寫 之前是用php

改完後發生的第一個問題就是中文全變成了???

192.168.105.61 || 2016-03-04 00:05:05 || 2016-03-07 00:05:05 || Flow Checking ????????????(1368>????:700) to Deny this IP cannot access network

原因是從mysql撈出來時中文就亂了 所以不管之後怎麼轉碼 都沒有用了
所以必須在撈時就要指定編碼 加上下方紅色字部分

db = MySQLdb.connect(host="localhost", user="abc", passwd="pwd", db="test", charset='utf8')

但加完後網頁反而出不來了
再查了一下資料 說是要再指定sys的編碼 於是程式內必需再加入以下三行

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

加完後之後的結果變成

192.168.105.61 || 2016-03-04 00:05:05 || 2016-03-07 00:05:05 || Flow Checking �訫�銝餅�����賊�蝬脰楝�輻�(1368>�𣂼��賊�:700) to Deny this IP cannot access network

看來中文有出來了 接下來是顯示的問題了 因為這個os比較久了 所以apache預設的編碼是設為big5 如果要去改會影響到其他東東 所以只能在程式加上指定編碼來處理了 比較新版本os的apache應該都預設為utf8了 應該不會碰到這個問題

print '<html>'
print '<head>'
print '<meta charset="UTF-8">'
print '</head>'
print '<body>'

print '</body>'
print '</html>'

網頁正常 搞定

192.168.105.61 || 2016-03-04 00:05:05 || 2016-03-07 00:05:05 || Flow Checking 違反主機連線數量網路政策(1368>限制數量:700) to Deny this IP cannot access network

完整程式碼如下

#!/usr/bin/python
# -*- coding: utf-8 -*-
print "Content-type: text/html"
print
# 引入 MySQL 模組
import MySQLdb
#引入 sys 並指定sys為utf-8編碼
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# 連接 MySQL
db = MySQLdb.connect(host="localhost", user="abc", passwd="pwd", db="test", charset='utf8')
cursor = db.cursor()
# 執行 SQL
cursor.execute("select ip from table;")
result = cursor.fetchall()
# 輸出結果
a=0
for record in result:
        if (a%2)==1:
                print "<FONT  COLOR=FF0000>"
        else:
                print "<FONT  COLOR=000000>"

        print record[0]
        print "<br>"
        print "<br>"
        a=a+1
db.close()

2016/03/04

因為python cgi的中文一直有問題出不來
找了好多資料
方法都不同
有的要轉碼
有的要用module
找到以下的方法
覺得是比較簡單的

#!/usr/bin/python
#encoding=utf-8  或  # -*- coding: utf8 -*-

print "Content-type: text/html"
print

print "Hi, Python."
print "中文"