Skip to content

Commit dac1c33

Browse files
authored
add new snippets
1 parent 244b7ea commit dac1c33

File tree

4 files changed

+186
-0
lines changed

4 files changed

+186
-0
lines changed

checksum_checking.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import hashlib
2+
3+
sha256_checksum_1 = hashlib.sha256()
4+
sha256_checksum_2 = hashlib.sha256()
5+
6+
path1 = 'test_checksum.txt'
7+
path2 = 'ddd.py'
8+
9+
with open(path1, "rb") as f:
10+
sha256_checksum_1.update(f.read())
11+
with open(path2, "rb") as f:
12+
sha256_checksum_2.update(f.read())
13+
14+
if sha256_checksum_1.hexdigest() == sha256_checksum_2.hexdigest():
15+
print('same')
16+
else:
17+
print('not same')

pgp_file_decryption.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import io
2+
import time
3+
from datetime import timedelta
4+
import psutil
5+
import addict
6+
import gnupg
7+
8+
9+
def get_memory_usage():
10+
process = psutil.Process()
11+
return process.memory_info().rss / (1024 ** 2)
12+
13+
14+
class GPGHandler:
15+
def __init__(self, gpg_private_ascii: str, passphrase: str):
16+
self.gpg_key = gnupg.GPG()
17+
self.passphrase = passphrase
18+
self.gpg_key.import_keys(gpg_private_ascii)
19+
try:
20+
self.gpg_key_id = self.gpg_key.list_keys()[-1]["keyid"]
21+
print(f"Using GPG_KEY_ID={self.gpg_key_id}")
22+
except IndexError:
23+
raise ValueError("No GPG key found")
24+
25+
def decrypt_file_object(self, encrypted_file_object):
26+
encrypted_file_object.seek(0)
27+
result = self.gpg_key.decrypt_file(encrypted_file_object, always_trust=True, passphrase=self.passphrase)
28+
if not result.ok:
29+
raise ValueError(f"Decryption failed. KEY_ID={result.key_id}, Status - {result.status}")
30+
decrypted_file_object = io.BytesIO(result.data)
31+
decrypted_file_object.seek(0)
32+
return decrypted_file_object
33+
34+
def encrypt_file_object(self, file_object: io.BytesIO) -> io.BytesIO:
35+
"""
36+
Encrypt a file object.
37+
"""
38+
encrypted_file_object = io.BytesIO()
39+
encrypted_file_object.write(
40+
self.gpg_key.encrypt(file_object.getvalue(), self.gpg_key_id, always_trust=True).data
41+
)
42+
encrypted_file_object.seek(0)
43+
return encrypted_file_object
44+
45+
46+
if __name__ == '__main__':
47+
memory_before = get_memory_usage()
48+
print("memory before", memory_before)
49+
50+
# read pgp file
51+
with open("13744603840.zip.pgp", "rb") as file:
52+
file_content = file.read()
53+
54+
# add secrets
55+
_secrets = addict.Dict(
56+
{
57+
"gpg_private_ascii": "",
58+
"gpg_pubring_passphrase": ""
59+
}
60+
)
61+
62+
_gpg_handler = GPGHandler(
63+
gpg_private_ascii=_secrets.gpg_private_ascii,
64+
passphrase=_secrets.gpg_pubring_passphrase,
65+
)
66+
_start = time.time()
67+
decrypted_content = _gpg_handler.decrypt_file_object(
68+
io.BytesIO(file_content),
69+
).read()
70+
_time_taken = str(timedelta(seconds=time.time() - _start))
71+
print(f"[DECRYPTION-COMPLETED with READING] for file, TimeTaken: {_time_taken}")
72+
memory_after = get_memory_usage()
73+
print("memory after", memory_after)

vault_updation_and_retrieval.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import hvac
2+
3+
MOUNT_POINT = '' # mount point - can be fleet/stack level or a single level
4+
5+
client = hvac.Client(
6+
url='https://vault.enterprise.company.co/',
7+
token='' # token you copy from UI
8+
)
9+
client.secrets.kv.v2.configure(
10+
mount_point=MOUNT_POINT
11+
)
12+
13+
# Check if the client is authenticated
14+
if not client.is_authenticated():
15+
raise Exception("Vault authentication failed")
16+
17+
clients = ['test1', 'test2']
18+
19+
for _client in clients:
20+
# Define the path to the secret
21+
secret_path = f'se/services/{_client}/sftp/'
22+
try:
23+
# Read the username from the specified path
24+
response = client.secrets.kv.v2.list_secrets(path=secret_path, mount_point=MOUNT_POINT)
25+
username = response['data']['keys']
26+
for each_username in username:
27+
# retrieve from vault
28+
response = client.secrets.kv.v2.read_secret_version(
29+
path=secret_path + each_username, mount_point=MOUNT_POINT)['data']['data']
30+
print(response)
31+
# update from vault
32+
response['host'] = "new-host"
33+
response['port'] = "22"
34+
client.secrets.kv.v2.create_or_update_secret(path=secret_path + each_username, secret=response,
35+
mount_point=MOUNT_POINT)
36+
print(f'update successful for: {each_username}')
37+
except Exception as exc:
38+
print(exc)

verify_sftp_connection.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
"""
2+
brew install corkscrew
3+
"""
4+
5+
import io
6+
import logging
7+
8+
from paramiko import RSAKey
9+
import fsspec
10+
import paramiko
11+
12+
logging.basicConfig()
13+
logging.getLogger("paramiko").setLevel(logging.DEBUG) # for example
14+
15+
16+
def with_proxy():
17+
# pkey = RSAKey.from_private_key(io.StringIO(credentials['private_key_ascii']))
18+
pkey = paramiko.Ed25519Key.from_private_key(io.StringIO(credentials['private_key_ascii']))
19+
pcommand = f'corkscrew {credentials["proxy_host"]} {credentials["proxy_port"]} %s %d' % (credentials['host'], credentials['port'])
20+
proxy = paramiko.proxy.ProxyCommand(pcommand)
21+
22+
authentication_kwargs = dict()
23+
authentication_kwargs["pkey"] = pkey
24+
authentication_kwargs["sock"] = proxy
25+
26+
fs = fsspec.filesystem(
27+
"sftp", host=credentials['host'], port=credentials['port'], username=credentials['username'], **authentication_kwargs
28+
)
29+
if fs:
30+
print("fs found:")
31+
files = fs.ls("/", detail=True)
32+
print("Files in the remote directory:")
33+
k = []
34+
for file in files:
35+
k.append(file['name'])
36+
print(sorted(k))
37+
38+
39+
def without_proxy():
40+
pkey = RSAKey.from_private_key(io.StringIO(credentials['private_key_ascii']))
41+
authentication_kwargs = dict()
42+
authentication_kwargs["pkey"] = pkey
43+
44+
fs = fsspec.filesystem(
45+
"sftp", host=credentials['host'], port=credentials['port'], username=credentials['username'], **authentication_kwargs
46+
)
47+
if fs:
48+
print("fs found:")
49+
files = fs.ls("/", detail=True)
50+
print("Files in the remote directory:")
51+
for file in files:
52+
print(file['name'])
53+
54+
55+
if __name__ == '__main__':
56+
credentials = {"host": "sftp.bloomberg.com", "port": 22, "username": "", "proxy_host": "", "proxy_port": 8080}
57+
58+
with_proxy()

0 commit comments

Comments
 (0)