In your example, the 4 corners wouldn't get selected because they are connected to 2 edges.
However there is a handy operator with SHIFT + G or Select>Select Similar then "Amount of connecting edges"
Alternatively, if used in a script, you can use the operator :
bpy.ops.mesh.select_similar(type='EDGE', threshold=0.01)
But you need to first select some vertices.
If you can't select the vertices before running your script, use this :
import bpy
import bmesh
mesh = bpy.context.object.data # Get selected object's mesh
bm = bmesh.from_edit_mesh(mesh)
# Create new edit mode bmesh to easily acces mesh data
for v in bm.verts:
v.select = select_set(len(v.link_edges) in (2,3) )
# Select all vertices that have 2 or 3 links and deselect the others
bmesh.update_edit_mesh(mesh) # Transfer the data back to the object's mesh