自动上传截图至github并获取uri

on under auxilary
2 minute read

0x00 about

目的:实现一个自动将截图上传至github并获取对应uri
用途:方便博客md文件中截图的处理
使用方法:
    初次运行时,在linxu系统中新建/root/pic目录,并将github上对应的图片目录下载到本地
    以后运行时,将需要上传的图片人工拷贝到/root/pic目录,运行该脚本可实现自动将新图片上传并获取uri
快捷运行:
    cp mysnippingtool.py /usr/share
    vi ~/.zshrc
    +alias jt="python /usr/share/mysnippingtool.py"

0x01 code

# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
#必须加上上面四行,否则各种编码的错误爆出

import os

tmp=0
all_file_name_list=[]
def get_all_file_name(folder):
    global tmp
    global root_dir
    global all_file_name_list
    tmp+=1
    if tmp==1:
        if folder[-1]=='/':
            root_dir=folder[:-1]
        else:
            root_dir=folder

    allfile=os.listdir(folder)
    for each in allfile:
        each_abspath=os.path.join(folder,each)
        if os.path.isdir(each_abspath):
            get_all_file_name(each_abspath)
        else:
            #print each_abspath
            if len(each_abspath)>len(root_dir)+1+len(os.path.basename(each)):
                filename=each_abspath[len(root_dir)+1:]
                #print filename
                all_file_name_list.append(filename)
            else:
                #print each
                all_file_name_list.append(each)

    return all_file_name_list


def main():
    if os.path.exists('/root/pic') is False:
        print "this is the first time you use me,or you have deleted /root/pic,I will mkdir /root/pic and git pull the github's pic.git,please put pngs to /root/pic when needed,and don't delet any png file in this folder"
        os.system("mkdir /root/pic && cd /root/pic && git init && git pull https://github.com/3xp10it/pic.git && git remote add origin https://github.com/3xp10it/pic.git && git status")

    os.system("cd /root/pic && git add . && git status && git commit -a -m 'update' && git push -u origin master")

    all_png_list=get_all_file_name("/root/pic")

    for each in all_png_list:
        if each[-3:]=='png':
            try:
                f=open("/root/pic/address.txt","a+")
                all=f.readlines()
                each_addr="https://raw.githubusercontent.com/3xp10it/pic/master/%s" % each
                if each_addr+'\r\n' not in all:
                    print each_addr
                    f.write(each_addr+'\r\n')
                    f.close()
            except:
                print "open /root/pic/address.txt wrong"

if __name__=='__main__':
    main()

0x02 attention

os.path.abspath()函数的问题

print os.path.abspath(each) is not good function,
it will get /root/桌面/spider_wooyun when I put this py script file in /root/桌面,and run:
(cd 桌面)
python mysnippingtool.py
it will get "/root/桌面/spider_wooyun" as a result,but the true result should be "/root/pic/spider_wooyun"
so I use:
        each_abspath=os.path.join(folder,each)
to get the current file's abspath

代码链接

github, python, 文件遍历
home
github
archive
category