Of course! Using Python with TeamViewer can be a powerful way to automate remote access, manage devices, or integrate remote support capabilities into your own applications.
There are two primary ways to interact with TeamViewer using Python:
- Automating the TeamViewer GUI: Using libraries like
pyautoguito control the TeamViewer application on your desktop. This is like a robot that moves your mouse and types for you. - Using the TeamViewer API: This is the recommended and most powerful method. It allows your Python script to communicate directly with TeamViewer's servers to perform actions like listing computers, generating sessions, and getting online status without ever needing to open the GUI.
Let's break down both methods.
Method 1: Automating the TeamViewer GUI with pyautogui
This approach is useful for simple, repetitive tasks within the TeamViewer application itself. For example, you could write a script to automatically accept incoming support sessions.
How it works: You use the pyautogui library to find images of buttons or elements on the screen and then simulate mouse clicks and keyboard inputs.
Prerequisites
- Install
pyautogui:pip install pyautogui
- Install Tesseract-OCR (for optional text-based detection):
pyautoguican also use OCR to read text on the screen, which can make your scripts more robust. On Windows, you can install it via tesseract-ocr-w64-setup-v5.3.0.20251214.exe. On macOS,brew install tesseract. On Linux,sudo apt-get install tesseract-ocr.
Example: Automatically Accept a Support Session
Let's imagine you want a script that looks for an "Accept" button in the incoming connection window and clicks it.
import pyautogui
import time
import sys
# Add a safety feature to move the mouse to a corner to stop the script
pyautogui.FAILSAFE = True
print("Script started. Move mouse to top-left corner to abort.")
try:
# Keep the script running
while True:
# Define the path to your 'accept_button.png' image
# You must take a screenshot of the button yourself!
accept_button_path = 'accept_button.png'
try:
# Locate the button on the screen
# confidence=0.8 is useful for slight variations in the image
button_location = pyautogui.locateOnScreen(accept_button_path, confidence=0.8)
if button_location:
print("Accept button found!")
# Get the center of the button's location
center = pyautogui.center(button_location)
# Move the mouse to the center and click
pyautogui.moveTo(center.x, center.y, duration=0.5)
pyautogui.click()
print("Clicked accept button. Waiting for next session...")
# Wait a bit before starting to search again
time.sleep(60)
else:
# If the button is not found, wait a second and try again
time.sleep(1)
except pyautogui.ImageNotFoundException:
# This exception is raised if the image is not found
# We can just continue the loop
time.sleep(1)
except KeyboardInterrupt:
print("\nScript stopped by user.")
sys.exit()
How to use this example:
- Open your TeamViewer application.
- Take a screenshot of the "Accept" button in the incoming connection window.
- Save that image as
accept_button.pngin the same directory as your Python script. - Run the script. It will continuously watch your screen for that button and click it when it appears.
Pros:
- Simple to get started.
- Can perform any action a human can do in the GUI.
Cons:
- Brittle: If TeamViewer updates its UI, your script will break.
- Slow: It has to constantly take screenshots and analyze them.
- Unreliable: It can be confused by overlapping windows or screen resolution changes.
- Not for server use: It requires a graphical desktop environment.
Method 2: Using the TeamViewer API (Recommended)
This is the professional way to integrate TeamViewer into your Python projects. You interact with TeamViewer's cloud services to manage your computers and sessions.
How it works: You make HTTPS requests to TeamViewer's API endpoints. You'll need an Access Token to authenticate.
Step 1: Get Your TeamViewer API Access Token
- Log in to your TeamViewer Management Console.
- Go to Developers -> API & Apps.
- Click Create App.
- Give your app a name (e.g., "Python Automation Script").
- Select the scopes (permissions) your app needs. For example:
computers(to list and manage your computers)sessions(to start and list sessions)reporting(to get reports)
- Click Create App.
- You will be given an Access Token. Treat this like a password! Copy and save it securely. You will not be able to see it again.
Step 2: Install a Request Library
We'll use the popular requests library.
pip install requests
Step 3: Write the Python Script
Here are some common examples of what you can do with the API.
Example 1: List All Your Computers
import requests
import json
# --- CONFIGURATION ---
# Replace with your actual API Access Token
API_TOKEN = "your_api_token_here"
API_BASE_URL = "https://webapi.teamviewer.com/api/v2"
# --- API REQUEST ---
def list_computers():
"""Fetches and prints a list of all computers in the account."""
headers = {
"Authorization": f"Bearer {API_TOKEN}"
}
try:
response = requests.get(f"{API_BASE_URL}/computers", headers=headers)
# Raise an exception for bad status codes (4xx or 5xx)
response.raise_for_status()
computers = response.json()
print("--- Your TeamViewer Computers ---")
for computer in computers.get('computers', []):
print(f"ID: {computer['id']}")
print(f"Name: {computer['computer_name']}")
print(f"Online: {computer['online']}")
print(f"Alias: {computer['alias']}")
print("-" * 20)
except requests.exceptions.HTTPError as err:
print(f"HTTP Error: {err}")
print("Check your API Token and permissions (scopes).")
except requests.exceptions.RequestException as err:
print(f"An error occurred: {err}")
if __name__ == "__main__":
list_computers()
Example 2: Start a Remote Control Session
import requests
import json
# --- CONFIGURATION ---
API_TOKEN = "your_api_token_here"
API_BASE_URL = "https://webapi.teamviewer.com/api/v2"
# --- API REQUEST ---
def start_remote_session(computer_id):
"""Starts a remote control session for a given computer ID."""
headers = {
"Authorization": f"Bearer {API_TOKEN}",
"Content-Type": "application/json"
}
# The API requires the ID in the URL body
url = f"{API_BASE_URL}/sessions/{computer_id}/remotecontrol"
try:
response = requests.post(url, headers=headers)
response.raise_for_status()
# The response contains a URL to the session
session_data = response.json()
print(f"Session started successfully!")
print(f"Session URL: {session_data['url']}")
print(f"You can open this URL in a web browser to connect.")
except requests.exceptions.HTTPError as err:
print(f"HTTP Error: {err}")
if response.status_code == 403:
print("Error: You don't have permission to control this computer or it's offline.")
elif response.status_code == 404:
print("Error: Computer ID not found.")
except requests.exceptions.RequestException as err:
print(f"An error occurred: {err}")
if __name__ == "__main__":
# Replace with the ID of the computer you want to control
# You can get this ID from the 'list_computers' script
target_computer_id = 123456789
start_remote_session(target_computer_id)
Pros:
- Robust and reliable: It's the official way to interact with TeamViewer.
- Fast and efficient: No GUI overhead.
- Powerful: Can be used for automation, monitoring, and integration with other services.
- Scalable: Can be run on servers without a desktop.
Cons:
- Requires initial setup to get an API token.
- Requires understanding of REST APIs and HTTP requests.
Summary: Which Method Should You Use?
| Feature | GUI Automation (pyautogui) |
TeamViewer API |
|---|---|---|
| Use Case | Simple, repetitive GUI tasks. | Automation, integration, management, server-side scripts. |
| Reliability | Low (breaks with UI updates). | High (official, stable endpoints). |
| Performance | Slow (screen scraping). | Fast (direct API calls). |
| Complexity | Low to Medium. | Medium (requires API knowledge). |
| Environment | Requires a desktop GUI. | Works on servers and headless systems. |
For almost all automation and integration projects, the TeamViewer API is the clear winner. Use the GUI automation method only for very specific, simple tasks where using the API would be overkill.
