teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

1

実際のコードを記載していなかったため、加筆いたしました。

2020/07/31 11:58

投稿

Shinjuku1904
Shinjuku1904

スコア16

title CHANGED
@@ -1,1 +1,1 @@
1
- Pythonを使って、ファイルの中身を成形したい
1
+ 【内容加筆】Pythonを使って、ファイルの中身を成形したい
body CHANGED
@@ -1,7 +1,8 @@
1
- Pythonで、sshで接続した先にある、テキストファイルを読み込んで、中身を書き換えたいと考えております。
1
+ Pythonで、sshで接続した先にある、テキストファイルを読み込んで、中身を書き換え、「JSON形式の文字列にしたいと考えております。
2
- ---------------------------------------------------------------------------------------
3
- ※sshで接続した先にあるファイルを読み込んで表示するだけまではできています。
4
2
 
3
+ ※コードはAWSのlambdaに取り込んで動作させたいと考えております。
4
+ ※sshで接続した先にあるファイルを読み込んで表示することはできています。
5
+
5
6
  具体的には、test.txtの中身が
6
7
 
7
8
  a
@@ -14,17 +15,54 @@
14
15
 
15
16
  {"数字1": 100, "数字2": 200, "数字3": 300}
16
17
 
17
- という形に成形したいと考えております。
18
+ という形に成形したいす。
18
19
 
19
- "検討していたコード"
20
+ エラーとしては以下の通りです。
20
- stdin, stdout, stderr = client.exec_command('cat home/etc/test.txt')
21
+ Syntax error in module 'lambda_function': invalid syntax
21
22
 
23
+ 実際のコードは以下の通りになります。
24
+ ``````python
25
+ import paramiko
26
+ import boto3
22
- lines = stdout.read()
27
+ import datetime
28
+ import os
23
29
 
30
+ print('Loading testdata lambda function')
31
+ today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y%m%d')
32
+ #now = datetime.datetime.now()
24
- file_contents = '{"数字1":' + lines[2] + ', "数字2": ' + lines[4] + ', "数字3": ' + lines[5]}'
33
+ yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y%m%d')
25
34
 
26
- のような形かなと思ったのですが、エラーしております。
35
+ def lambda_handler(event, context):
27
- どのように修正すればよろしいでしょうか。
28
- または、別の形でも構いません。
29
36
 
37
+ #接続先情報の設定
38
+ client = paramiko.SSHClient()
39
+ client.set_missing_host_key_policy(paramiko.WarningPolicy())
40
+ user = os.environ['ID']
41
+ passwd = os.environ['PASS']
42
+ ip = os.environ['IP']
43
+ client.connect(ip,port=22,username=user,password=passwd)
44
+
45
+ #接続先サーバー実行コマンド
46
+ stdin, stdout, stderr = client.exec_command('cat /home/tmp/test.txt')
47
+
48
+ # アップロードファイルの内容格納
49
+ lines = stdout.read()
50
+ file_contents = '{"数字1": ' + lines[2] + ', "数字2": ' + lines[4] + ', "数字3": ' + lines[5]}'
51
+ print(file_contents)
52
+ file_contents = file_contents.replace('\n','')
53
+ print(file_contents)
54
+ client.close()
55
+ bucket = os.environ['BUCKET']
56
+
57
+ #取得ファイルの保存
58
+ key = 'Testdata/' + 'json/' + today + '/' +'testdata_' + yesterday + '.json'
59
+ print(key)
60
+ s3 = boto3.resource('s3')
61
+ obj = s3.Object(bucket,key)
62
+ obj.put(Body=file_contents)
63
+ return
64
+ ```
65
+
66
+
67
+
30
68
  ご教授のほどよろしくお願いいたします。