반응형
googledriveapi

Upload File to Google Drive

Prepare

구글 사이트에서 준비 작업이 필요하다.
https://console.developers.google.com/flows/enableapi?apiid=drive
프로젝트 생성
Google Drive API 사용.
Credential에서 OAuth 화면.
Product Name 입력.
json 파일 다운 로드 (client_drive.json).
작업디렉터리로 파일 이동.

# 파이썬 패키지 설치
pip install google-api-python-client

토큰 생성

from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

scopes = 'https://www.googleapis.com/auth/drive.file'
store = file.Storage('storage.json')
creds = store.get()

try :
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

if not creds or creds.invalid:
    print('make new cred')
    flow = client.flow_from_clientsecrets('client_drive.json', scopes)
    creds = tools.run_flow(flow, store, flags) if flags else tools.run_flow(flow, store)


콘솔로 위의 파일을 실행하면, 웹브라우저가 뜨고, 구글 인증/로그인을 하면 된다. 현재 폴더에 storage.json 이라는 토큰이 생김. 보안 파일이므로 중요보관.

파일 업로드

from oauth2client.client import GoogleCredentials
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

store = file.Storage('storage.json')
creds = store.get()
drive = build('drive', 'v3', http=creds.authorize(Http()))
uploadfiles=( ('a.txt'),)
for f in uploadfiles:
    fname = f
    metadata={'name':fname, 'mimeType':None}
    res = drive.files().create(body=metadata, media_body=fname).execute()
    if res:
        print('upload %s'%fname)
        

파일 다운로드

파일ID는 구글드라이브에서 해당 파일 공유하기해서 링크 주소를 얻어오면 id값이 들어있다.

import io
from apiclient.http import MediaIoBaseDownload

results = drive.files().list(pageSize=10,fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
    print('No files found.')
else:
    print('Files:')
    for item in items:
        print(item)
        print('{0} ({1})'.format(item['name'], item['id']))

#https://drive.google.com/open?id=1SY8FS1QcGTknYJjEUgaqj1ucWEtESTn3
# request = drive.files().export_media(fileId='a.txt', mimeType=EXCEL)
request = drive.files().get_media(fileId='1SY8FS1QcGTknYJjEUgaqj1ucWEtESTn3')
fh = io.FileIO('b.txt', 'wb')
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print('Download %d%%.' % int(status.progress() * 100))
        

CoLab에서 구글 드라이브 파일 가져오기


# Install the PyDrive wrapper & import libraries.  
# This only needs to be done once per notebook. 
!pip install -U -q PyDrive 
from pydrive.auth import GoogleAuth 
from pydrive.drive import GoogleDrive 
from google.colab import auth 
from oauth2client.client import GoogleCredentials 

# Authenticate and create the PyDrive client.  
# This only needs to be done once per notebook. 
auth.authenticate_user() 
gauth = GoogleAuth() 
gauth.credentials = GoogleCredentials.get_application_default() 
drive = GoogleDrive(gauth) 

# Download a file based on its file ID.  
#  
# A file ID looks like: laggVyWshwcyP6kEI-y_W3P8D26sz 
file_id = 'REPLACE_WITH_YOUR_FILE_ID' 
downloaded = drive.CreateFile({'id': file_id}) print('Downloaded content "{}"'.format(downloaded.GetContentString()))  

  


Written with StackEdit.

'Python' 카테고리의 다른 글

Jupyter Notebook 멀티라인출력  (0) 2019.09.19
진행(progress)바/ tqdm  (2) 2019.08.28
Fourier Transform Python  (1) 2019.08.02
[UI] Qt5  (0) 2019.05.17
두 선분의 교차여부 체크  (0) 2019.04.11
반응형
java_rsa_test

JAVA RSA Test

RSA 알고리즘으로 JAVA에서 키쌍(공개키, 개인키)를 생성해 보고,
암복호화 및 서명 검증 테스트를 해보자.

package test_tryexcept;

import java.io.*;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import org.apache.commons.codec.binary.Base64;

public class RSATest {

	public static void main(String[] args) throws IllegalBlockSizeException, BadPaddingException {

		// Create Key Pair . (public key, private key)
		System.out.println("1. create key pair -----------------------------");
		PublicKey publicKey1 = null;
		PrivateKey privateKey1 = null;

		SecureRandom secureRandom = new SecureRandom();
		KeyPairGenerator keyPairGenerator;
		try {
			keyPairGenerator = KeyPairGenerator.getInstance("RSA");
			keyPairGenerator.initialize(512, secureRandom);

			KeyPair keyPair = keyPairGenerator.genKeyPair();
			publicKey1 = keyPair.getPublic();
			privateKey1 = keyPair.getPrivate();

			KeyFactory keyFactory1 = KeyFactory.getInstance("RSA");
			RSAPublicKeySpec rsaPublicKeySpec = keyFactory1.getKeySpec(publicKey1, RSAPublicKeySpec.class);
			RSAPrivateKeySpec rsaPrivateKeySpec = keyFactory1.getKeySpec(privateKey1, RSAPrivateKeySpec.class);
			System.out.println("Public  key modulus : " + rsaPublicKeySpec.getModulus());
			System.out.println("Public  key exponent: " + rsaPublicKeySpec.getPublicExponent());
			System.out.println("Private key modulus : " + rsaPrivateKeySpec.getModulus());
			System.out.println("Private key exponent: " + rsaPrivateKeySpec.getPrivateExponent());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		}

		// 2. key save to file. (base64 encoding)
		System.out.println("\n2. save key file -----------------------------");
		byte[] bPublicKey1 = publicKey1.getEncoded();
		String sPublicKey1 = Base64.encodeBase64String(bPublicKey1);
		byte[] bPrivateKey1 = privateKey1.getEncoded();
		String sPrivateKey1 = Base64.encodeBase64String(bPrivateKey1);

		try {
			BufferedWriter bw1 = new BufferedWriter(new FileWriter("PublicKey.txt"));
			bw1.write(sPublicKey1);
			bw1.newLine();
			bw1.close();
			BufferedWriter bw2 = new BufferedWriter(new FileWriter("PrivateKey.txt"));
			bw2.write(sPrivateKey1);
			bw2.newLine();
			bw2.close();
			System.out.println("PublicKey.txt, PrivateKey.txt file saved.") ;
		} catch (IOException e) {
			e.printStackTrace();
		}

		// 3. load key file
		System.out.println("\n3. load key file -----------------------------");
		String sPublicKey2 = null;
		String sPrivateKey2 = null;

		BufferedReader brPublicKey = null;
		BufferedReader brPrivateKey = null;
		try {
			brPublicKey = new BufferedReader(new FileReader("PublicKey.txt"));
			sPublicKey2 = brPublicKey.readLine();
			brPrivateKey = new BufferedReader(new FileReader("PrivateKey.txt"));
			sPrivateKey2 = brPrivateKey.readLine();
			System.out.println("load PubilcKey.txt, PrivateKey.txt");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (brPublicKey != null)
					brPublicKey.close();
				if (brPrivateKey != null)
					brPrivateKey.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		// key string to key data. 
		byte[] bPublicKey2 = Base64.decodeBase64(sPublicKey2.getBytes());
		PublicKey publicKey2 = null;
		byte[] bPrivateKey2 = Base64.decodeBase64(sPrivateKey2.getBytes());
		PrivateKey privateKey2 = null;
		try {
			KeyFactory keyFactory2 = KeyFactory.getInstance("RSA");
			X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(bPublicKey2);
			publicKey2 = keyFactory2.generatePublic(publicKeySpec);
			PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(bPrivateKey2);
			privateKey2 = keyFactory2.generatePrivate(privateKeySpec);
		} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
			e.printStackTrace();
		}

		// 4. encrypt test
		System.out.println("\n4. encrypt test -----------------------------");

		String sPlain1 = "This is an example.";
		String sPlain2 = null;
		try {
			Cipher cipher = Cipher.getInstance("RSA");
			System.out.println("input:"+ sPlain1);
			// 공개키 이용 암호화
			cipher.init(Cipher.ENCRYPT_MODE, publicKey2);
			byte[] bCipher1 = cipher.doFinal(sPlain1.getBytes());
			String sCipherBase64 = Base64.encodeBase64String(bCipher1);
			System.out.println("encrypt(pubkey):"+sCipherBase64);

			// 개인키 이용 복호화
			byte[] bCipher2 = Base64.decodeBase64(sCipherBase64.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, privateKey2);
			byte[] bPlain2 = cipher.doFinal(bCipher2);
			sPlain2 = new String(bPlain2);
			System.out.println("decrypt(prikey):"+sPlain2);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}

		///////////////////////////////////////////////////////////////////////
		// 5. digital sign test
		System.out.println("\n5. digital sign test -----------------------------");
		try {
			Cipher cipher = Cipher.getInstance("RSA");
			
			// sign
			Signature rsa = Signature.getInstance("SHA1withRSA"); 
			rsa.initSign(privateKey2);
			rsa.update(sPlain1.getBytes());
			byte[] ds = rsa.sign();
			
			String dsBase64 = Base64.encodeBase64String(ds) ;
			System.out.println("signature:"+dsBase64);
			
			// verify by pubkey
			rsa.initVerify(publicKey2);
			rsa.update(sPlain1.getBytes());
			boolean bret = rsa.verify(ds);
			System.out.println("verify:"+bret);
			
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (SignatureException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

결과

1. create key pair -----------------------------
Public  key modulus : 8248696551746632304090375750090525095455249159692340933778807179048823058050266268679997440009797868855529133651252439721233111988778274617606294142148157
Public  key exponent: 65537
Private key modulus : 8248696551746632304090375750090525095455249159692340933778807179048823058050266268679997440009797868855529133651252439721233111988778274617606294142148157
Private key exponent: 7921703957617548721899753716754620427893524678607141706686365641426276369846256193464100508658766225776306979668612467878281049443630080785215985430577793

2. save key file -----------------------------
PublicKey.txt, PrivateKey.txt file saved.

3. load key file -----------------------------
load PubilcKey.txt, PrivateKey.txt

4. encrypt test -----------------------------
input:This is an example.
encrypt(pubkey):NHeP0KvZpgqd/yE5HEbh5v/kuOP6jvKE8+y9wJb1p7Nt0SOlJrFrtkn+i+75h2d2EiSBZBxBAMErsG7wp6BN3A==
decrypt(prikey):This is an example.

5. digital sign test -----------------------------
signature:KSsmktqxCDjmy4mHMxT+aUb/y2m7b4B9zq1jxMixGs7J8dPTqyKD5LJkXgNwIm4pY6JIn9YotxwyWUP3hjzaXA==
verify:true

Written with StackEdit.

반응형
TensorBoardRemote

Jupyter Lab/ TensorBoard remote monitoring through firewall

서버 방화벽으로 6006포트가 막힌 원격 PC에서 서버의 텐서보드를 모니터링하는 방법! & 같은 방법으로 서버의 jupyter lab을 원격 PC에서 여러 개 접속하기

서버 환경에서 python 코드를 돌려 tensorboard 로그가 쌓이고 있는 상황에서 서버에서 tensorboard를 보려면 일단 텐서보드 서버를 아래와 같이 실행한다. (로그 경로 지정)

$ tensorboard --logdir="./log"

이렇게 로그 폴더만 지정해 주고, 서버의 웹 브라우저에서
http://localhost:6006 으로 접속하면 된다.

그리고 해당 서버의 6006 포트가 방화벽으로 막혀 있지 않다면 원격 PC에서 위 http 주소에 localhost대신 서버 ip를 지정해주면 볼 수 있다.

만약 방화벽으로 막혀있으면 당연 접속이 안될 것인데, 우회하는 방법이 있다.

원리는 바로 ssh로 port forwarding을 이용하는 것이다. (당연히 서버에 ssh 포트는 방화벽으로 열려있어야 한다.)

위와 같은 조건에서 PC에 16006 포트를 만들고 이 포트와 서버의 6006 포트를 ssh로 연결한다.

PC에서 서버로 ssh 접속을 다음과 같이 한다. (윈도우면 cmd창을 띄우고 작업)

 ssh -L 16006:localhost:6006 [ID]@[ServerIP]

서버의 ssh 포트번호가 22가 아니면 -p [port] 를 추가한다.
ssh 접속이 완료되면, PC에서 브라우저를 띄우고 아래 주소로 접속
http://localhost:16006
이미지 001

Jupyter Lab Remote Connect

Jupyter Lab이나 Jupyter Notebook도 마찬가지로 서버의 로컬에서만 접속 가능한 경우에 원격 접속을 위해 동일하게 처리할 수 있다.
먼저 안전하게 설정 파일 생성과 접속암호를 아래와 같이 만든다.

$jupyter notebook --generate-config
$jupyter notebook password
암호 입력

암호 설정 방법은 수동으로도 할 수 있다. ~/.jupyter/ 폴더 내에 생성된 설정 파일을 보면 복잡하지만 가능하다. 간단하게 하려면 위 방식을 이용하자.

서버에서 작업할 디렉터리로 이동 후, 쥬피터 랩 실행

$ jupyter lab
... http://localhost:port ...

위와 같이 포트 번호를 안내해 준다. 이미 할당되어 있으면 변경되므로 확인.
(쥬피터를 디렉터리를 달리하여 여러 개 실행할 수도 있다.)

PC에서 서버로 ssh 접속을 다음과 같이 한다. (윈도우면 cmd창을 띄우고 작업) -L 뒤에 PC포트:localhost:서버포트
서버 포트는 서버 연결포트이니 당연히 쥬피터 포트를 보고 입력해 준다.

 ssh -L 8890:localhost:8890 [ID]@[ServerIP]

PC에서 로컬호스트의 생성한 PC포트로 접속한다. (위와 같이 PC포트 서버 포트가 일치할 필요는 없다. 로컬 포트는 할당되지 않은 임의의 포트로 지정해도 된다.)
http://localhost:8890
암호를 입력하고 연결하면 된다.

jupyterlab

Written with StackEdit.

+ Recent posts