Skip to content
Projects
Groups
Snippets
Help
This project
Loading...
Sign in / Register
Toggle navigation
S
soporte-backup-db
Overview
Overview
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Jesús
soporte-backup-db
Commits
3e28e748
Commit
3e28e748
authored
Apr 15, 2026
by
Javier
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Actualizo funciones de subida de ficheros pcloud
parent
a82a22d4
Hide whitespace changes
Inline
Side-by-side
Showing
5 changed files
with
137 additions
and
52 deletions
+137
-52
.env
.env
+6
-0
conector_db.py
conector_db.py
+23
-0
create_backup_db_soporte.py
create_backup_db_soporte.py
+1
-1
setup_hyperv.py
setup_hyperv.py
+4
-4
upload_pcloud_backup.py
upload_pcloud_backup.py
+103
-47
No files found.
.env
View file @
3e28e748
...
@@ -17,3 +17,8 @@ PWD_SFTP_TRUENAS=_RW!2k14
...
@@ -17,3 +17,8 @@ PWD_SFTP_TRUENAS=_RW!2k14
HOST_SFTP_TRUENAS2='192.168.2.240'
HOST_SFTP_TRUENAS2='192.168.2.240'
USER_SFTP_TRUENAS2=ftp_backup
USER_SFTP_TRUENAS2=ftp_backup
PWD_SFTP_TRUENAS2=_RW!2k14
PWD_SFTP_TRUENAS2=_RW!2k14
SQLSERVER_SERVER=192.168.2.200
SQLSERVER_DATABASE=bdd_wifi
SQLSERVER_USERNAME=bdbackupservice
SQLSERVER_PASSWORD=bdbs2k21
\ No newline at end of file
conector_db.py
0 → 100644
View file @
3e28e748
import
pyodbc
import
os
from
dotenv
import
load_dotenv
load_dotenv
()
def
connect_db_sql
():
"""
Conexión a la base de datos db_wifi(SQL)
Return:
cnx_db_wifi : Conexión a la Base de datos
"""
sql_server_hostname
=
os
.
getenv
(
"SQLSERVER_SERVER"
)
sql_server_database
=
os
.
getenv
(
"SQLSERVER_DATABASE"
)
sql_server_username
=
os
.
getenv
(
"SQLSERVER_USERNAME"
)
sql_server_password
=
os
.
getenv
(
"SQLSERVER_PASSWORD"
)
try
:
cnx_db_wifi
=
pyodbc
.
connect
(
f
"DRIVER=FreeTDS;server={sql_server_hostname};PORT=1433;DATABASE={sql_server_database};UID={sql_server_username};PWD={sql_server_password};TDS_Version=7.0"
,
ansi
=
True
)
if
cnx_db_wifi
is
None
or
cnx_db_wifi
==
'Null'
:
cnx_db_wifi
=
pyodbc
.
connect
(
f
"DRIVER=FreeTDS;server={sql_server_hostname};PORT=1433;DATABASE={sql_server_database};UID={sql_server_username};PWD={sql_server_password};TDS_Version=7.0"
,
ansi
=
True
)
return
cnx_db_wifi
except
Exception
as
e
:
print
(
f
" Fallo al conectarse con la base de datos SQL. {e}"
)
create_backup_db_soporte.py
View file @
3e28e748
...
@@ -34,7 +34,7 @@ def eliminar_archivos_antiguos_ftp(ftp):
...
@@ -34,7 +34,7 @@ def eliminar_archivos_antiguos_ftp(ftp):
# Obtiene la lista de archivos en el directorio
# Obtiene la lista de archivos en el directorio
archivos
=
ftp
.
nlst
()
archivos
=
ftp
.
nlst
()
# Fecha límite para la eliminación de archivos
# Fecha límite para la eliminación de archivos
fecha_limite
=
datetime
.
now
()
-
timedelta
(
days
=
7
)
fecha_limite
=
datetime
.
now
()
-
timedelta
(
days
=
14
)
for
archivo
in
archivos
:
for
archivo
in
archivos
:
# Obtiene la información del archivo
# Obtiene la información del archivo
...
...
setup_hyperv.py
View file @
3e28e748
from
create_backup_db_soporte
import
create_backup_database_soporte
,
upload_sftp_file
from
create_backup_db_soporte
import
create_backup_database_soporte
,
upload_sftp_file
from
upload_pcloud_backup
import
upload_solo_pcloud_
sp
,
delete_file_date
from
upload_pcloud_backup
import
upload_solo_pcloud_
new
,
delete_file_date_new
if
__name__
==
'__main__'
:
if
__name__
==
'__main__'
:
#Crea copia de seguridad y lo almacena en la carpeta backups
#Crea copia de seguridad y lo almacena en la carpeta backups
create_backup_database_soporte
()
create_backup_database_soporte
()
correct
=
upload_sftp_file
()
correct
=
upload_sftp_file
()
if
correct
:
if
correct
:
#Sube a Pcloud la backups
#Sube a Pcloud la backups
upload_backups_soporte_pcloud
=
upload_solo_pcloud_
sp
(
True
)
upload_backups_soporte_pcloud
=
upload_solo_pcloud_
new
(
)
if
upload_backups_soporte_pcloud
:
if
upload_backups_soporte_pcloud
:
#Borra fichero en Pcloud si su fecha de creación es anterior a 25 dias
#Borra fichero en Pcloud si su fecha de creación es anterior a 25 dias
delete_file_date
()
delete_file_date_new
()
\ No newline at end of file
\ No newline at end of file
upload_pcloud_backup.py
View file @
3e28e748
...
@@ -4,62 +4,118 @@ from pcloud import PyCloud
...
@@ -4,62 +4,118 @@ from pcloud import PyCloud
from
os
import
remove
from
os
import
remove
from
datetime
import
datetime
,
timedelta
from
datetime
import
datetime
,
timedelta
import
pytz
import
pytz
import
requests
from
conector_db
import
connect_db_sql
from
requests_toolbelt.multipart.encoder
import
MultipartEncoder
PCLOUD_API
=
"https://eapi.pcloud.com"
def
get_pcloud_token
():
"""Obtiene el token de pCloud desde la tabla Parametros."""
cnx
=
connect_db_sql
()
cursor
=
cnx
.
cursor
()
cursor
.
execute
(
"SELECT ApiTokenPcloud FROM [bdd_wifi].[dbo].[TB_Parametros]"
)
row
=
cursor
.
fetchone
()
cursor
.
close
()
cnx
.
close
()
if
not
row
:
raise
ValueError
(
"No se encontró el token de pCloud en la tabla Parametros."
)
return
row
[
0
]
def
upload_solo_pcloud_new
():
def
upload_solo_pcloud_sp
(
hyperV
:
bool
=
False
):
"""
"""
Subida de la backup almacenada en la carpeta Backup a Pcloud
Sube los ficheros de backup a pCloud usando la API REST con token OAuth2.
El token se obtiene de la tabla Parametros.
"""
"""
#Compruebo si el fichero esta descargado, si esta descargado inicio la subida a pcloud
directorio
=
pathlib
.
Path
(
'soporte-backup-db/backups'
)
.
absolute
()
directorio
=
pathlib
.
Path
(
'soporte-backup-db/backups'
)
.
absolute
()
with
os
.
scandir
(
directorio
)
as
ficheros
:
with
os
.
scandir
(
directorio
)
as
f
:
ficheros
=
[
fichero
.
path
for
fichero
in
ficheros
if
fichero
.
is_file
(
ficheros
=
[
fi
.
path
for
fi
in
f
if
fi
.
is_file
()]
)]
if
ficheros
:
if
not
ficheros
:
#pc = PyCloud('informatica@rentelwifi.com', '_RW!2k14', endpoint="eapi")
print
(
"Fichero inexistente en la carpeta backups"
)
pc
=
PyCloud
(
'info@rentel.pro'
,
'Rw20_J!214'
,
endpoint
=
"eapi"
)
return
False
pc
.
listfolder
(
folderid
=
0
)
if
hyperV
:
token
=
get_pcloud_token
()
pc
.
uploadfile
(
files
=
ficheros
,
path
=
'/Rentel_Wifi/Backup/Hyper-V/Soporte'
)
else
:
for
fichero
in
ficheros
:
pc
.
uploadfile
(
files
=
ficheros
,
path
=
'/Rentel_Wifi/Backup/Soporte'
)
with
open
(
fichero
,
"rb"
)
as
f
:
nombre
=
os
.
path
.
basename
(
fichero
)
print
(
ficheros
)
m
=
MultipartEncoder
(
for
fichero
in
ficheros
:
# Borramos ficheros de la carpeta backups
fields
=
{
remove
(
fichero
)
"file"
:
(
nombre
,
f
,
"application/octet-stream"
)
return
True
}
#print('Subido a Pcloud')
)
resp
=
requests
.
post
(
f
"{PCLOUD_API}/uploadfile"
,
params
=
{
"access_token"
:
token
,
"path"
:
"/Backup/Hyper-V/Soporte"
,
"filename"
:
nombre
,
"nopartial"
:
1
},
data
=
m
,
headers
=
{
"Content-Type"
:
m
.
content_type
}
)
else
:
resultado
=
resp
.
json
()
print
(
"Fichero inexistente en la carpeta backups"
)
if
resultado
.
get
(
"result"
)
==
0
:
print
(
f
'Subido fichero: {nombre} a pCloud /Backup/Hyper-V/Soporte'
)
remove
(
fichero
)
else
:
print
(
f
'Error subiendo {nombre} a pCloud: {resultado}'
)
return
False
return
True
def
delete_file_date
():
def
delete_file_date_new
():
"""Borra fichero en Pcloud si su fecha de creación es anterior a 30 dias
Arg (Pcloud): Conexión Pcloud
Return (list): Nombre de los ficheros borrados en caso que los haya.
"""
"""
deletes_files
=
[]
# Ficheros borrados
Borra ficheros en pCloud /Backup/Hyper-V/Soporte
#pc = PyCloud('informatica@rentelwifi.com', '_RW!2k14', endpoint="eapi")
cuya fecha de creación sea anterior a 30 días.
pc
=
PyCloud
(
'info@rentel.pro'
,
'Rw20_J!214'
,
endpoint
=
"eapi"
)
"""
folder_path
=
"/Rentel_Wifi/Backup/Hyper-V/Soporte"
token
=
get_pcloud_token
()
folder_info
=
pc
.
listfolder
(
path
=
folder_path
)
limite
=
datetime
.
now
()
-
timedelta
(
days
=
30
)
for
item
in
folder_info
[
"metadata"
][
"contents"
]:
#Recorro los ficheros de la carpeta
file_time
=
item
[
"created"
]
# Listar ficheros de la carpeta
if
compare_date_file
(
file_time
):
#Si la fecha del fichero es anterior a 30 dias de antiguedad
resp
=
requests
.
get
(
f
"{PCLOUD_API}/listfolder"
,
params
=
{
#Compruebo que el fichero que vamos a borrar pertenece a dentro de la ruta folder_path
"access_token"
:
token
,
item_path
=
item
[
'path'
]
"path"
:
"/Backup/Hyper-V/Soporte"
if
comprobar_item_a_borrar
(
item_path
,
folder_path
):
})
#Borar fichero
resultado
=
resp
.
json
()
pc
.
deletefile
(
fileid
=
item
[
"fileid"
])
deletes_files
.
append
(
item
[
"name"
])
if
resultado
.
get
(
"result"
)
!=
0
:
print
(
f
"Error listando carpeta pCloud: {resultado}"
)
if
len
(
deletes_files
)
==
0
:
return
False
print
(
"No hay ficheros para borrar en Pcloud que sean más antiguos de 30 dias."
)
else
:
contents
=
resultado
.
get
(
"metadata"
,
{})
.
get
(
"contents"
,
[])
print
(
"Ficheros borrados de Pcloud "
)
print
(
deletes_files
)
for
item
in
contents
:
if
item
.
get
(
"isfolder"
):
continue
# pCloud devuelve la fecha en formato "Day, DD Mon YYYY HH:MM:SS +0000"
fecha_str
=
item
.
get
(
"created"
,
""
)
try
:
fecha
=
datetime
.
strptime
(
fecha_str
,
"
%
a,
%
d
%
b
%
Y
%
H:
%
M:
%
S
%
z"
)
.
replace
(
tzinfo
=
None
)
except
ValueError
:
print
(
f
"No se pudo parsear la fecha de: {item.get('name')} → {fecha_str}"
)
continue
if
fecha
<
limite
:
fileid
=
item
.
get
(
"fileid"
)
nombre
=
item
.
get
(
"name"
)
del_resp
=
requests
.
get
(
f
"{PCLOUD_API}/deletefile"
,
params
=
{
"access_token"
:
token
,
"fileid"
:
fileid
})
if
del_resp
.
json
()
.
get
(
"result"
)
==
0
:
print
(
f
"Fichero eliminado de pCloud: {nombre} (creado: {fecha.date()})"
)
else
:
print
(
f
"Error eliminando {nombre}: {del_resp.json()}"
)
return
True
def
compare_date_file
(
file_time_create
:
str
):
def
compare_date_file
(
file_time_create
:
str
):
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment