1
我正在編寫一個小腳本來加密位於特定路徑之後的每個文件。在我的情況下,腳本realpath ... 在第一個文件夾(腳本目錄)中工作正常,但是當我轉到下一個目錄時,它嘗試將光盤放入位於第二個目錄層的文件中。 所以樹看起來像[文件,文件,文件夾[文件,文件],文件,文件]獲取每個目錄的文件(Py)
(我知道,腳本和密鑰也會被加密,但我還是懶得這樣做。 ..和我的英語不好對不起,我希望你能理解我:P)
我的代碼:
import os
import Crypto
from Crypto.PublicKey import RSA
def cryptFilesInFolder(currentDir):
content_list = os.listdir(currentDir)
print content_list
print '[+] Start encrypting files in Dir: ' + currentDir
for filename in content_list:
print '[+] Encrypting ' + filename
crypt(filename, key, currentDir)
def crypt(filename, key, currentDir):
try:
f = open(filename, 'r')
fileString = f.read()
f.close()
print '[+] Encrypting file: ' + filename + ' with 4096 bytes'
encryptedFileString = key.publickey().encrypt(fileString, 4096)
f = open (filename, 'w')
f.write(str(encryptedFileString)) #write ciphertext to file
f.close()
except IOError:
print '[!] File was a folder'
cryptFilesInFolder(currentDir + '/' + filename)
print '[+] Startet Crypting'
print '[+] Reading Key'
f = open('mykey.pem','r')
key = RSA.importKey(f.read())
f.close()
print '[+] Key imported'
print '[+] Setting Root Directory'
rootDir = os.path.realpath(__file__)
print 'Root Directory set'
print '[+] Starting encryption in folder: '
cryptFilesInFolder(os.path.dirname(os.path.realpath(__file__)))
print '[+] Finished \n\n\n'
錯誤消息:
Bjarne-2:crypt bjarne$ python crypt\ folder\ Kopie.py
[+] Startet Crypting
[+] Reading Key
[+] Key imported
[+] Setting Root Directory
Root Directory set
[+] Starting encryption in folder:
['.DS_Store', 'crypt folder Kopie.py', 'myKey.pem', 'Neuer Ordner']
[+] Start encrypting files in Dir: /Users/bjarne/Desktop/crypt
[+] Encrypting .DS_Store
[+] Encrypting file: .DS_Store with 4096 bytes
[+] Encrypting crypt folder Kopie.py
[+] Encrypting file: crypt folder Kopie.py with 4096 bytes
[+] Encrypting myKey.pem
[+] Encrypting file: myKey.pem with 4096 bytes
[+] Encrypting Neuer Ordner
[!] File was a folder
['.DS_Store', 'key Kopie.py']
[+] Start encrypting files in Dir: /Users/bjarne/Desktop/crypt/Neuer Ordner
[+] Encrypting .DS_Store
[+] Encrypting file: .DS_Store with 4096 bytes
[+] Encrypting key Kopie.py
[!] File was a folder
Traceback (most recent call last):
File "crypt folder Kopie.py", line 37, in <module>
File "crypt folder Kopie.py", line 11, in cryptFilesInFolder
File "crypt folder Kopie.py", line 25, in crypt
File "crypt folder Kopie.py", line 11, in cryptFilesInFolder
File "crypt folder Kopie.py", line 25, in crypt
File "crypt folder Kopie.py", line 6, in cryptFilesInFolder
OSError: [Errno 20] Not a directory: '/Users/bjarne/Desktop/crypt/Neuer Ordner/key Kopie.py'